簡體   English   中英

Python正則表達式:findall()和search()

[英]Python regex: findall() and search()

我有以下Python正則表達式:

>>> p = re.compile(r"(\b\w+)\s+\1")

\\b :單詞邊界
\\w+ :一個或多個字母數字字符
\\s+ :一個或多個空格(可以是 \\t\\n ,..)
\\1 :反向引用組1(= (..)之間的部分)

這個正則表達式應該找到一個單詞的所有重復出現-如果兩個出現是彼此相鄰的,並且它們之間有一些空格。
使用搜索功能時,正則表達式似乎可以正常工作:

>>> p.search("I am in the the car.")

<_sre.SRE_Match object; span=(8, 15), match='the the'>

正如我所期望the the ,找到的匹配項是。 奇怪的行為是在findall函數中:

>>> p.findall("I am in the the car.")

['the']

找到的匹配項現在僅the 為什么會有所不同?

在正則表達式中使用組時, findall()僅返回組; 文檔中

如果該模式中存在一個或多個組,則返回一個組列表;否則,返回一個列表。 如果模式包含多個組,則這將是一個元組列表。

在使用反向引用時,您不能避免使用組,但是可以在整個模式周圍放置一個新組:

>>> p = re.compile(r"((\b\w+)\s+\2)")
>>> p.findall("I am in the the car.")
[('the the', 'the')]

外部組是組1,因此后向引用應指向組2。您現在有兩個組,因此每個條目有兩個結果。 使用命名組可能會使此內容更具可讀性:

>>> p = re.compile(r"((?P<word>\b\w+)\s+(?P=word))")

您可以將其過濾回僅外部組結果:

>>> [m[0] for m in p.findall("I am in the the car.")]
['the the']

暫無
暫無

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

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