我总是很难理解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在最后一个之后,我可能有任何字符/字符串。。。你知道吗
正则表达式是强大的,但有时它们过于致命。字符串方法应该可以用更少的思想完成您需要的任务
此程序与您请求的模式匹配。你知道吗
参考:http://docs.python.org/2/library/re.html
演示:http://ideone.com/aZjjVj
相关问题 更多 >
编程相关推荐