【问题标题】:Find complicated substring with wildcards Python使用通配符 Python 查找复杂的子字符串
【发布时间】:2018-06-04 15:36:06
【问题描述】:

我正在尝试在长字符串中定位表达式的位置。该表达式的工作原理如下。它由 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”)的地方。我研究了正则表达式通配符,但我很难将它与列表的不同元素以及通配符的可变长度放在一起。

感谢任何建议!

【问题讨论】:

  • 'a blaa a bli blubb d' 也是有效结果吗?
  • 是的,我明白你的意思,该示例选择不当,因此我对其进行了编辑。这种模式自然不会出现在文本中......

标签: python string wildcard


【解决方案1】:

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

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

【讨论】:

  • 哇,你打败了我。我有一个几乎相同的解决方案!一些小的差异,我的最终输出模式看起来像 (\W+|^)((a|b)\W+(\w+\W+){1,5}(c|d))(\W+|$) 以允许在行尾的开头有多个非单词字符,我使用 for m in pattern.finditer(text): print(m.start(2)) 而不使用非捕获组,只需从迭代器中获取第二组.
  • @Davos 将其发布为第二种方式 :)
  • 不,我不认为它的不同足以保证超过评论:)
猜你喜欢
  • 2013-07-04
  • 1970-01-01
  • 2016-01-20
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 2022-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多