RegEx look-behind'(?<= \ n | \ A)'因可变长度而不起作用
我使用Python(3)并需要一个正则表达式,它匹配字符串的开头或右边的换行符。RegEx look-behind'(?<= n | A)'因可变长度而不起作用
我必须添加re.DOTALL
标志,因为我需要一次处理多行。这里的例子只是简化了。
我想出什么样的主意是这样的回顾后:
(?<=\n|\A)start of line
我测试了它on regex101.com在那里工作,但在我的Python 3.5的控制台上运行它会导致这个错误回溯:
$ python3
Python 3.5.1+ (default, Mar 30 2016, 22:46:26)
[GCC 5.3.1 20160330] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> re.search(r'(?<=\n|\A)start of line', 'just any text to test', re.DOTALL)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/re.py", line 173, in search
return _compile(pattern, flags).search(string)
File "/usr/lib/python3.5/re.py", line 293, in _compile
p = sre_compile.compile(pattern, flags)
File "/usr/lib/python3.5/sre_compile.py", line 540, in compile
code = _code(p, flags)
File "/usr/lib/python3.5/sre_compile.py", line 525, in _code
_compile(code, p.data, flags)
File "/usr/lib/python3.5/sre_compile.py", line 158, in _compile
raise error("look-behind requires fixed-width pattern")
sre_constants.error: look-behind requires fixed-width pattern
>>>
什么我可以用它来克服这个限制吗?
由于\A
不是一个字符,该错误信息是有道理的。
尝试,当你在你的正则表达式中使用.
这个代替
re.search(r'^start of line', 'just any text to test', re.MULTILINE)
DOTALL才有意义。
也许regex101使用第三方regex包而不是标准库中的re。
>>> import regex
>>> regex.search(r'(?<=\n|\A)line', 'test\nline')
<regex.Match object; span=(5, 9), match='line'>
正如你可以看到,正则表达式接受可变宽度回顾后的图案。
是的,我知道在这个例子中我不需要DOTALL,但我真正的一个更复杂,并且匹配那里有多行。但是,MULTILINE标志加'^'as模式起作用,谢谢。 –
Regex101使用与'regex' PyPi模块不同的东西。它只是Python选项的越野车。 –
regex101通过使用PCRE引擎实现Python风格,通过防止正则表达式使用Python中不具备的功能运行。它适用于大多数情况,除了一些特殊情况。 – nhahtdh
使用多标志,这将导致^
和$
匹配每一个开始,分别行尾,从而使你的正则表达式只是:
^
使用're.DOTALL'不会阻止您使用're.MULTILINE'。有了这个,它只是'^ pattern'。 –
只是fyi。你不需要为零长度的'\ A'使用后视。您可以使用['(?:(?