我正在使用 python 逐行搜索文件的部分和子部分。
*** Section with no sub section
*** Section with sub section ***
*** Sub Section ***
*** Another section
部分以 0-2 个空格开头,后跟三个星号,子部分有 2+ 个空格,然后是星号。
我写出没有“***”的部分/子部分;目前(使用 re.sub)。
Section: Section with no sub section
Section: Section with sub section
Sub-Section: Sub Section
Section: Another Section
问题 1:是否有一个带有捕获组的 python 正则表达式可以让我将部分/子部分名称作为捕获组访问?
问题 2:正则表达式组如何允许我标识部分或子部分(可能基于 match.group 中 /content 的数量)?
示例(非工作):
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
以前的尝试 我已经能够使用单独的正则表达式和 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、答案和其他研究。我现在花更多的时间来捕捉这些词:
^[a-zA-Z]+$
并计算星号匹配的数量以确定“级别”。我仍在寻找一个单一的正则表达式来匹配两个 - 三个“组”。可能不存在。
谢谢。