regex
module已經命名列表(實際上套):
#!/usr/bin/env python
import regex as re # $ pip install regex
p = re.compile(r"\L<words>", words=['fun', 'dum', 'sun', 'gum'])
if p.search("I love to have fun."):
print('matched')
這裏words
只是一個名字,你可以使用你喜歡的任何東西來代替。
.search()
使用方法而不是指定列表之前/之後的.*
。
要使用STDLIB的re
模塊模擬命名名單:
#!/usr/bin/env python
import re
words = ['fun', 'dum', 'sun', 'gum']
longest_first = sorted(words, key=len, reverse=True)
p = re.compile(r'(?:{})'.format('|'.join(map(re.escape, longest_first))))
if p.search("I love to have fun."):
print('matched')
re.escape()
被用來逃跑的正則表達式元字符,如.*?
個別字內(從字面上匹配的話)。
sorted()
模擬regex
行爲,並首先將其最長的單詞的備選方案中,比較:
>>> import re
>>> re.findall("(funny|fun)", "it is funny")
['funny']
>>> re.findall("(fun|funny)", "it is funny")
['fun']
>>> import regex
>>> regex.findall(r"\L<words>", "it is funny", words=['fun', 'funny'])
['funny']
>>> regex.findall(r"\L<words>", "it is funny", words=['funny', 'fun'])
['funny']
來源
2015-10-29 10:19:04
jfs
加入與'數組元素|'膠,將形成的字符串作爲'樂趣|達姆|太陽| gum'這可以在正則表達式中使用。 – Tushar
're.search('|'.join(string_lst),input_string)' –
'any(z in string_list for z in re.findall(r「['\ w] +」,'這只是爲了好玩') )' –