[英]how to use python regular expressions to pull any word that comes before or after a comma?
[英]How to use python regular expressions to return a list of strings that comes before and after a certain pattern?
例如
s = "Before\=String TARGETA After\=String limbo nonsense Before\=String TARGETB After\=String ..... Before\=String TARGETC After\=String"
結果列表應為:
['TARGETA','TARGETB','TARGETC']
我試過了
regex = '.*Before\=String(.*?)After\=String.*'
matches = re.search(regex, val).groups()
>> (' TARGETC ',)
問題在於它僅返回最后一項。
您需要使用re.findall()
而不是re.search()
,並從開頭和結尾刪除.*
元素:
regex = r'Before\\=String(.*?)After\\=String'
matches = re.findall(regex, val)
演示:
>>> import re
>>> s = "Before\=String TARGETA After\=String limbo nonsense Before\=String TARGETB After\=String ..... Before\=String TARGETC After\=String"
>>> regex = r'Before\\=String(.*?)After\\=String'
>>> re.findall(regex, s)
[' TARGETA ', ' TARGETB ', ' TARGETC ']
注意,這仍然包括空格; 如果您也不想包含它,請在(...)
捕獲組之前和之后添加\\s*
。
使用re.findall()
返回所有匹配項的列表,並確保如果您的實際字符串中確實包含反斜杠,則將其加倍轉義。 您可以刪除前導/尾隨.*
因為無需找到這些子字符串,並在捕獲組之前和之后使用\\s*
來占用多余的空白。
>>> import re
>>> s = 'Before\=String TARGETA After\=String limbo nonsense Before\=String TARGETB After\=String ..... Before\=String TARGETC After\=String'
>>> re.findall(r'Before\\=String\s*(.*?)\s*After\\=String', s)
['TARGETA', 'TARGETB', 'TARGETC']
尚不清楚您的反斜杠是否真的在目標字符串中。 如果它們是匹配的並且需要匹配,則需要將它們成對放在正則表達式中,因為簡單的\\=
將僅匹配等號。
re.search
不會執行您要求的操作,因為它只會在目標字符串中找到模式的第一個匹配項。 您也不需要正則表達式核心的.*
前后,因為(除非使用re.match
),模式可以匹配目標字符串中的任何位置 ,而不必全部匹配。
re.findall
功能是您需要的功能。 無需返回MatchObject
而是僅返回目標字符串中與模式匹配的所有子字符串的列表。 或者,如果模式中有任何組,它將返回與這些組匹配的子字符串,而不是整個模式所匹配的子字符串。
下面的代碼允許在前后標記的內容前后留有可選的空格。 另外,如果您希望在單獨的行上定義正則表達式,則也可以在那里進行編譯。 re.X
標志值允許將不重要的空格添加到正則表達式中,以使其更具可讀性。
import re
val = "Before\=String TARGETA After\=String limbo nonsense Before\=String TARGETB After\=String ..... Before\=String TARGETC After\=String"
regex = re.compile(r' Before\\=String \s* (.*?) \s* After\\=String ', flags=re.X)
matches = re.findall(regex, val)
print(matches)
輸出
['TARGETA', 'TARGETB', 'TARGETC']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.