簡體   English   中英

使用貪婪運算符的Python正則表達式搜索

[英]Python regex search with greedy operator

我正在嘗試使用正則表達式來查找表達式,這就是我正在嘗試做的

import re
h1= open("test.txt")
for ln in h1:
    ln = ln.rstrip()
    if re.search("^From:.+@", ln):
        print(ln)

按照邏輯,它應該在“ @”處停止搜索,但是在我沒有發生的情況下,我得到以下輸出:從:ray@media.berkeley.edu

我也嘗試使用限定詞'?' 但它似乎不起作用。 有人可以建議為什么它不起作用,或者我如何使用正則表達式使它特別起作用。

您正在打印整行,而可以執行以下操作:

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是您唯一需要的東西,那么您可以嘗試這樣的事情。

問題:

1.您不應打印整行。

2.您應使用^From:[^@]+來防止匹配@

在此處嘗試此代碼段

import re
h1= open("test.txt")
for ln in h1:
    ln = ln.rstrip()
    result = re.search("^From:[^@]+", ln)
    if result is not None:
        print(result.group(0))

在這里嘗試正則表達式演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM