簡體   English   中英

正則表達式搜索並grep字符串中第一個關鍵字和第二個關鍵字的第二次出現之間的所有內容 - Python

[英]Regex search and grep everything between the second occurrence of first keyword and second keyword in a string - Python

example_string = 'Hello A Bye, Hello B Ciao."

通緝: "B"

我想用什么: re.search()

正常做法:

res = re.search(r'Hello(.*?)Ciao', example_string)

但是這種方法會輸出: "A Bye, Hello B"

有沒有辦法告訴程序第二次出現第一個關鍵字。 因此,在這種情況下,它將搜索字符串中第二次出現的單詞“Hello”,並將其作為res第一個關鍵字。

這樣它就會簡單地輸出: "B"

有誰知道如何解決這個問題?

謝謝。

我們可以在這里使用re.findall查找所有匹配項,然后訪問第二個匹配項:

example_string = "Hello A Bye, Hello B Ciao."
matches = re.findall(r'\bHello (\w+)', example_string)
print(matches[1])  # B

使用re.findall可以工作, findall() 可能是 re 模塊中最強大的函數。 上面我們使用 re.search() 來查找模式的第一個匹配項。 findall() 查找所有匹配項並將它們作為字符串列表返回,每個字符串代表一個匹配項。

例子: -

text = "He was carefully disguised but captured quickly by police."
>>> re.findall(r"\w+ly", text)
>>> ['carefully', 'quickly']

暫無
暫無

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

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