regex
模块有命名列表(实际上是集合):
import regex as re
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
模块模拟命名列表:
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']
|
作为粘合剂将数组元素连接起来,将形成字符串fun|dum|sun|gum
,可以在正则表达式中使用。 - Tusharre.search('|'.join(string_lst), input_string)
- Avinash Rajany(z in string_list for z in re.findall(r"['\w]+", 'This is just for fun'))
- Burhan Khalid