带贪婪运算符的Python正则表达式搜索
我试图使用正则表达式来找到一个表达式,下面是我要做的带贪婪运算符的Python正则表达式搜索,python,regex,Python,Regex,我试图使用正则表达式来找到一个表达式,下面是我要做的 import re h1= open("test.txt") for ln in h1: ln = ln.rstrip() if re.search("^From:.+@", ln): print(ln) 根据逻辑,它应该在“@”处停止搜索,但是在我的情况下,我没有得到以下输出: 发件人:ray@media.berkeley.edu 我还尝试使用限定符“?”,但它似乎不起作用。是否有人可以建议它为什么不起作用
import re
h1= open("test.txt")
for ln in h1:
ln = ln.rstrip()
if re.search("^From:.+@", ln):
print(ln)
根据逻辑,它应该在“@”处停止搜索,但是在我的情况下,我没有得到以下输出:
发件人:ray@media.berkeley.edu
我还尝试使用限定符“?”,但它似乎不起作用。是否有人可以建议它为什么不起作用,或者我如何使用regex使它特别起作用。如果要打印整行,可以改为:
print(ln.split('@')[0])
正则表达式解决方案:
# regex = r"(.+?)@"
import re
h1= open("test.txt")
regex = r"(.+?)@"
for ln in h1:
ln = ln.rstrip()
matches = re.search(regex, ln)
if matches:
for groupNum in range(0, len(matches.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = matches.start(groupNum), end = matches.end(groupNum), group = matches.group(groupNum)))
通过拆分和使用startswith的其他方式:
h1= open("test.txt")
for ln in h1:
if ln.startswith("From: "):
print(ln.split("@")[0])
# Output From: ray
如果
Regex
是您唯一要找的东西,那么您可以尝试这样的东西
问题:
# regex = r"(.+?)@"
import re
h1= open("test.txt")
regex = r"(.+?)@"
for ln in h1:
ln = ln.rstrip()
matches = re.search(regex, ln)
if matches:
for groupNum in range(0, len(matches.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = matches.start(groupNum), end = matches.end(groupNum), group = matches.group(groupNum)))
1。不应打印整行
2.您应该使用^From:[^@]+
来防止匹配@
你想得到什么?我的预期输出应该是:“From:ray”,它不应该超过“@”新手111尝试这个正则表达式
From:[^@]+
是的,不幸的是,正则表达式是一个要求。From:[^@]+尝试使用它,但它不起作用。仍然得到相同的输出。非常感谢@salparadise是的,这对我以前也很有用。但是,我想知道这是否与以前的python版本有所不同。因为我上面提到的代码在打印时没有实际指定split()函数。所以我想这是让它工作的唯一方法?@Rookie111更好的方法让它工作,看看正则表达式和非正则表达式的答案。@Rookie111检查上面的答案,我已经提供了正则表达式。非常感谢@Sahil Gulati,这很有效!我能提取出这个表达。非常感谢大家。。这真的很有帮助。我现在已经让正则表达式工作了。