Python regex可选的捕获组或lastindex

2024-10-16 17:20:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python逐行搜索文件中的节和子节。在

   *** Section with no sub section
  *** Section with sub section ***
           *** Sub Section ***
  *** Another section

部分以0-2个空格开头,后跟三个星号,子部分有2+空格,然后是星号。在

我写出没有“***”的章节/小节;目前(使用re.sub公司). 在

^{pr2}$

问题1:是否有一个带有捕获组的python regexp可以让我以捕获组的形式访问节/子节名称?在

问题2:regexp组如何允许我标识节或子节(可能基于匹配组)? 在

示例(非工作):

match=re.compile('(group0 *** )(group1 section title)(group2 ***)')
sectionTitle = match.group(1)
if match.lastindex = 0: sectionType = section with no subs
if match.lastindex = 1: sectionType = section with subs
if match.lastindex = 2: sectionTpe = sub section

以前的尝试 我已经能够用单独的regexp和if语句捕获部分或子部分,但我想一次完成所有操作。像下面这条线的东西;有第二组贪婪的麻烦。在

'(^\*{3}\s)(.*)(\s\*{3}$)'

我似乎无法让贪婪的人或可选择的小组一起工作。http://pythex.org/对这一点很有帮助。在

此外,我还尝试捕获星号“(*{3})”,然后根据找到的组的数量来确定是部分还是子部分。在

sectionRegex=re.compile('(\*{3})'
m=re.search(sectionRegex)
  if m.lastindex == 0:
       sectionName = re.sub(sectionRegex,'',line) 
       #Set a section flag
  if m.lastindex ==1:
       sectionName = re.sub(sectionRegex,''line)
       #Set a sub section flag.

谢谢 也许我完全错了。感谢任何帮助。在

最新更新 我一直在玩Pythex,answers和其他研究。我现在花更多的时间来捕捉这些词:

^[a-zA-Z]+$

并计算星号匹配的数量来确定“级别”。我仍然在搜索一个regexp来匹配两到三个“组”。可能不存在。在

谢谢。在


Tags: noreifmatchwithsection星号subs
3条回答

QUESTION 1: Is there a python regexp with capture groups that would let me access the section/sub section names as a capture group?

a single regexp to match the two - three "groups". May not exist

是的,这是可以做到的。我们可以将条件分解为以下树:

  • 行首+0到2个空格
  • 两种交替:
    1. ***+任何文本[组1]
    2. 1+空格+***+任何文本[group 2]
  • ***(可选)+行尾


上面的树可以用以下模式表示:

^[ ]{0,2}(?:[*]{3}(.*?)|[ ]+[*]{3}(.*?))(?:[*]{3})?$

注意子节被不同的组捕获([组1][组2])。它们都使用相同的语法.*?,都带有一个lazy quantifier (the extra "?"),以允许结尾的可选"***"匹配。在


QUESTION 2: How would the regexp groups allow me to ID section or sub section (possibly based on the number of /content in a match.group)?

上述regex只在组1中捕获部分,而子节仅在组2中捕获。为了在代码中更容易识别,我将使用^{}并使用^{}检索捕获。在

代码:

^{pr2}$

为了引用每个/小节,您可以使用以下方法之一,而不是打印dict:

match.group("Section")
match.group(1)
match.group("SubSection")
match.group(2)

正则表达式:

(^\s+)(\*{3})([a-zA-Z\s]+)(\*{3})*

捕获3或4个组,如下所述。在

^{pr2}$

假设您的意思是子部分有3个以上的空格,您可以这样做:

import re

data = '''
  *** Section with no sub section
*** Section with sub section ***
           *** Sub Section ***
 *** Another section
'''

pattern = r'(?:(^ {0,2}\*{3}.*\*{3} *$)|(^ {0,2}\*{3}.*)|(^ *\*{3}.*\*{3} *$))'

regex = re.compile(pattern, re.M)
print regex.findall(data)

这将为您提供如下分组:

^{pr2}$

相关问题 更多 >