使用通配符Python查找复杂的子字符串

时间:2018-06-04 15:36:06

标签: python string wildcard

我试图在长字符串中找到表达式的位置。表达式如下。它由list1的任何元素给出,后跟1到5个单词的通配符(用空格分隔),后跟list2的任何元素。例如:

list1=["a","b"], list2=["c","d"]
text = "bla a tx fg hg gfgf tzt zt blaa  a  bli blubb d  muh meh  muh d"

应该返回“37”,因为那是找到表达式(“a bli blubb d”)的地方。我查看了正则表达式的通配符,但我很难将它与列表的不同元素以及通配符的可变长度放在一起。

感谢任何建议!

1 个答案:

答案 0 :(得分:3)

你可以构建一个正则表达式:

import re

pref=["a","b"]
suff=["c","d"]

# the pattern is dynamically constructed from your pref and suff lists.
patt = r"(?:\W|^)((?:" + '|'.join(pref) + r")(?: +[^ ]+){1,5} +(?:" + '|'.join(suff) + r"))(?:\W|$)"

text = "bla a tx fg hg gfgf tzt zt blaa  a  bli blubb d  muh meh  muh d"

print(patt)

for k in re.findall(patt,text):
    print(k, "\n", text.index(k))

输出:

(?:\W|^)((?:a|b)(?: +[^ ]+){1,5} +(?:c|d))(?:\W|$)  # pattern
a  bli blubb d                                      # found text
33                                                  # position (your 37 is wrong btw.)

公平警告:这不是一个非常强大的方法。

正则表达式类似于:

Either start of line or non-text character (not captured) followed by
one of your prefs. followed by 1-n spaces, followed by 1-5 non-space things that 
are seperated by 1-n spaces, followed by something from suff followed
by (non captured non-Word-Character or end of line)

有关汇编正则表达式的演示和更完整的说明:请参阅https://regex101.com/r/WHZfr9/1