Skip to main content
 首页 » 编程设计

python之python中正则表达式的逻辑

2024年11月01日27davidwang456

我总是很难理解 python 中正则表达式的逻辑。

all_lines = '#hello\n#monica, how re "u?\n#hello#robert\necho\nfall and spring' 

我想检索以 # 开头的子字符串,直到最后一个 # 之后出现的第一个 \n - 即 '#hello\n#monica,你好吗?\n#hello#robert'

所以如果我尝试:

>>> all_lines = '#hello\n#monica, how re "u?\n#hello#robert\necho' 
>>> RE_HARD = re.compile(r'(^#.*\n)') 
>>> mo = re.search(RE_HARD, all_lines) 
>>> print mo.group(0) 
#hello 

现在,如果我对最后一个 # 之后的第一个\n 之后的内容进行硬编码,即,我对 echo 进行硬编码,我得到:

>>> all_lines = '#hello\n#monica, how re "u?\n#hello#robert\necho' 
>>> RE_HARD = re.compile(r'(^#.*echo)') 
>>> mo = re.search(RE_HARD, all_lines) 
>>> print mo.group(0) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: 'NoneType' object has no attribute 'group' 

我得到一个错误,不知道为什么。看起来和以前一样。

这仍然不是我想要的,因为实际上在最后一个 # 之后的第一个\n 之后我可能有任何字符/字符串......

请您参考如下方法:

此程序与您请求的模式匹配。

#!/usr/bin/python 
 
import re 
 
all_lines = '#hello\n#monica, how re "u?\n#hello#robert\necho' 
 
regex = re.compile( 
    r'''\#             # first hash 
        .*             # continues to (note: .* greedy) 
        \#             # last hash 
        .*?$           # rest of the line. (note .*? non-greedy) 
    ''', 
    # Flags:  
    #   DOTALL: Make the '.' match any character at all, including a newline 
    #   VERBOSE: Allow comments in pattern 
    #   MULTILINE: Allow $ to match end of line 
    re.DOTALL | re.VERBOSE | re.MULTILINE) 
 
print re.search(regex, all_lines).group() 

引用:http://docs.python.org/2/library/re.html
演示:http://ideone.com/aZjjVj