Python中文
首页
教程
问答
标签
搜索
登录
注册
Python regex可选的捕获组或lastindex
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我正在使用python逐行搜索文件中的节和子节。在</p> <pre><code> *** Section with no sub section *** Section with sub section *** *** Sub Section *** *** Another section </code></pre> <p>部分以0-2个空格开头,后跟三个星号,子部分有2+空格,然后是星号。在</p> <p>我写出没有“***”的章节/小节;目前(使用re.sub公司). 在</p> ^{pr2}$ <p><strong>问题1</strong>:是否有一个带有捕获组的python regexp可以让我以捕获组的形式访问节/子节名称?在</p> <p><strong>问题2</strong>:regexp组如何允许我标识节或子节(可能基于匹配组)? 在</p> <p><strong>示例(非工作):</strong></p> <pre><code>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 </code></pre> <p><strong>以前的尝试</strong> 我已经能够用单独的regexp和if语句捕获部分或子部分,但我想一次完成所有操作。像下面这条线的东西;有第二组贪婪的麻烦。在</p> <pre><code>'(^\*{3}\s)(.*)(\s\*{3}$)' </code></pre> <p>我似乎无法让贪婪的人或可选择的小组一起工作。<a href="http://pythex.org/" rel="nofollow">http://pythex.org/</a>对这一点很有帮助。在</p> <p>此外,我还尝试捕获星号“(*{3})”,然后根据找到的组的数量来确定是部分还是子部分。在</p> <pre><code>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. </code></pre> <p><strong>谢谢</strong> 也许我完全错了。感谢任何帮助。在</p> <p><strong>最新更新</strong> 我一直在玩Pythex,answers和其他研究。我现在花更多的时间来捕捉这些词:</p> <pre><code>^[a-zA-Z]+$ </code></pre> <p>并计算星号匹配的数量来确定“级别”。我仍然在搜索一个regexp来匹配两到三个“组”。可能不存在。在</p> <p>谢谢。在</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>正则表达式:</p> <pre><code>(^\s+)(\*{3})([a-zA-Z\s]+)(\*{3})* </code></pre> <p>捕获3或4个组,如下所述。在</p> ^{pr2}$
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
如何为此数据帧创建散点图?
2 回答
如何为此编写Django模板
7 回答
如何为此表达式编写正则表达式?
10 回答
如何为步进电机选择合适的值?
1 回答
如何为每15分钟间隔的日期时间行(在新列中)添加标签?
4 回答
如何为每一列创建汇总表?
9 回答
如何为每一组groupbyPandas做滚动“得到假人”
10 回答
如何为每一行分别运行函数(python)?
3 回答
如何为每一行生成一个随机数?
2 回答
如何为每一轮将pytorch模型输出存储到numpy
9 回答
如何为每个.py-fi文件创建单独的zip文件
7 回答
如何为每个<li class=”“><a>找到最近的上述同级<li>?
4 回答
如何为每个CSV列生成特定的文件?
7 回答
如何为每个csv文件使用read_csv,即使它是空的?PythonPandas
10 回答
如何为每个CSV文件创建单独的Pandas数据帧并给它们起有意义的名称?
10 回答
如何为每个datetime和每个id创建一行?
1 回答
如何为每个Django型号选择赋予不同的颜色
6 回答
如何为每个Django模型实例安排一个周期性的芹菜任务?
2 回答
如何为每个Django视图设置一个装饰器?
3 回答
如何为每个for循环迭代分配变量
5 回答