Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 要从行首匹配的正则表达式_Python_Regex - Fatal编程技术网

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

我想要一个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 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'

你的第二行%?你的第二行%?