python中regex的逻辑

2024-06-10 13:38:44 发布

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

我总是很难理解python中regex的逻辑。你知道吗

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

我想检索从#开始直到最后一个#之后的第一个\n的子串,即'#hello\n#monica, how re "u?\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在最后一个之后,我可能有任何字符/字符串。。。你知道吗


Tags: rehellosearchgroupallmonicaroberthow
2条回答

正则表达式是强大的,但有时它们过于致命。字符串方法应该可以用更少的思想完成您需要的任务

>>> my_string = '#hello\n#monica, how re "u?\n#hello#robert\necho\nfall and spring'
>>> hash_positions = [index for index, c in enumerate(my_string) if c == '#']
>>> hash_positions
[0, 7, 27, 33]
>>> first = hash_positions[0]
>>> last = hash_positions[-1]
>>> new_line_after_last_hash = my_string.index('\n',last)
>>> new_line_after_last_hash
40
>>> new_string = my_string[first:new_line_after_last_hash]
>>> new_string
'#hello\n#monica, how re "u?\n#hello#robert'

此程序与您请求的模式匹配。你知道吗

#!/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

相关问题 更多 >