繁体   English   中英

regEx在notepad ++中有效,但在python中无效

[英]regEx works in notepad++ but not in python

假设我们有这个:

.................
=== Operation 'abcd::ddca:dsd' ended in 1.234s   /1.234s (100.00%) execution time
................

使用记事本++,我可以通过以下方式识别此内容:

^\=* Operation '([\d\D]*)' ended in (\d*.\d*)s\s*/(\d*.\d*)s \([\d\D]*\) execution time

我希望将操作名称和执行时间分组。

在python中,尝试这样做:

exp=re.compile(r"^\=* Operation \'([\d\D]*)\' ended in (\d*.\d*)s\s*/(\d*.\d*)s \([\d\D]*\) execution time") 

什么也没提供。 我已经尝试了\\\\(用于转义文字括号,但是没有用。我猜测我不需要这样做,因为在构建对象表达式时使用了r“ [exp]”。

关于如何获得与notepad ++相同的结果的任何想法?

LE:仅在以下情况下尝试过:

exp=re.compile(r"^\=* Operation \'([\d\D]*)\'", flags=re.MULTILINE)

仍然找不到任何东西。

LE2:

稍后在代码中,我使用groups=exp.match(INPUT)并获得具有groups.group(n)

答案:问题是match 使用search 解决了问题

问题中提到的正则表达式对我来说没有任何变化。

>>> s = """
... .................
... === Operation 'abcd::ddca:dsd' ended in 1.234s   /1.234s (100.00%) execution time
... ................
... """
>>> import re
>>> exp = re.compile(r"^\=* Operation \'([\d\D]*)\' ended in (\d*.\d*)s\s*/(\d*.\d*)s \([\d\D]*\) execution time", flags=re.M)
>>> re.search(exp, s)
<_sre.SRE_Match object at 0x1038766b8>
>>> re.findall(exp, s)
[('abcd::ddca:dsd', '1.234', '1.234')]

但是要考虑两件事:

  1. 在flags参数中使用re.M
  2. 用户searchfindall方法进行匹配。 确保您没有使用re.match因为它将仅匹配字符串的开头。

我注意到abcd :: ddca:dsd的末尾有双引号

因此:

exp=re.compile(r"^\=* Operation '([\d\D]*)\" ended in (\d*\.\d*)s\s*/(\d*\.\d*)s \([\d\D]*\) execution time", flags=re.MULTILINE)

你需要让^一条线 ,不只是整个字符串的开头开始匹配:

exp=re.compile(r"^\=* Operation '([\d\D]*)' ended in (\d*\.\d*)s\s*/(\d*\.\d*)s \([\d\D]*\) execution time", flags=re.MULTILINE)

试试这个-我不是正则表达式专家,但这对我有用。

>>> i
"=== Operation 'abcd::ddca:dsd' ended in 1.234s   /1.234s (100.00%) execution time"
>>> exp = re.compile(r'^={3} Operation (.*?) ended in (\d+\.\d+s)(?:.*?)$')
>>> re.findall(exp,i)
[("'abcd::ddca:dsd'", '1.234s')]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM