Python 要从行首匹配的正则表达式
我想要一个python正则表达式,它匹配出现在一行中的所有Python 要从行首匹配的正则表达式,python,regex,Python,Regex,我想要一个python正则表达式,它匹配出现在一行中的所有文本,但前提是%没有出现在文本之前。例如,我希望匹配下面的第1行和第2行,但不匹配第3行: 1. some random stuff text and then something completely different 2. some random stuff text and % then something completely different 3. some random % stuff text and % then so
文本
,但前提是%
没有出现在文本
之前。例如,我希望匹配下面的第1行和第2行,但不匹配第3行:
1. some random stuff text and then something completely different
2. some random stuff text and % then something completely different
3. some random % stuff text and % then something completely different
我认为这很容易,因为我只需要从行首搜索一个不是%
的字符,或者换行符,后面跟着文本。由于我不理解以下代码的原因:
import re
lines = '''1. some random stuff text and then something completely different
2. some random stuff text and % then something completely different
3. some random % stuff text and then something completely different
'''
re.findall('^[^%\n\r]*text')
仅查找匹配的1。第一行有一些随机填充文本
,第二行没有匹配。另一方面,re.findall('[%\n\r]*text')
查找您期望的三个匹配项
有人知道我做错了什么吗?您需要设置选项re.MULTILINE
,以确保^
与新行匹配
import re
lines = '''1. some random stuff text and then something completely different
2. some random stuff text and % then something completely different
3. some random % stuff text and then something completely different
'''
result = re.findall('^[^%\n\r]*text', lines, re.MULTILINE)
print result
# prints: ['1. some random stuff text', '2. some random stuff text'
您需要设置选项re.MULTILINE
,以确保^
与新行匹配
import re
lines = '''1. some random stuff text and then something completely different
2. some random stuff text and % then something completely different
3. some random % stuff text and then something completely different
'''
result = re.findall('^[^%\n\r]*text', lines, re.MULTILINE)
print result
# prints: ['1. some random stuff text', '2. some random stuff text'
你的第二行%?你的第二行%?