在字符串中搜索子字符串的潜在组合

2024-06-09 17:45:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个string,一个array,其中包含该字符串可能的结束字符,还有一个要解析的文本块。例如:

stringText = "something"
endChars = [",", ".", ";", " "]
textBlock = "This string may contain something;"

在一行if语句中,我想检查textBlock是否包含stringText后跟任何一个endChars。我很确定我可以用python2.7中内置的any函数来实现这一点,但到目前为止我的努力都失败了。我有类似的东西:

if re.search(stringText + any(endChar in endChars), textBlock, re.IGNORECASE):
    print("Match")

我看过this的帖子,但是我很难把它应用到上面的检查中。如有任何帮助,我们将不胜感激。你知道吗

编辑:

除了上述内容之外,是否可以确定在字符串中找到了endChars中的哪一个?使用@SCB下面的答案并对其进行修改,我希望下面的内容能够做到这一点,但它抛出了一个未定义的错误。你知道吗

stringText = "something"
endChars = [",", ".", ";", " "]
textBlock = "This string may contain something;"

if any((stringText + end).lower() in textBlock.lower() for end in endChars):
    print("Match on " + end)

预期输出:Match on ;

实际输出

更新 我已经找到了这个问题的合适的解决方案,至少符合我的要求。它不是一条直线,但它确实起作用。为完整起见,如下所示

for end in endChars:
    if stringText + end in textBlock:
        print("Match on " + end)

Tags: 字符串instringifonmatchanythis
3条回答

非正则表达式解决方案:

stringText = "something"
endChars = [",", ".", ";", " "]
textBlock = "This string may contain something;"
if any((stringText+i in textBlock for i in endChars):
   #condition met
   pass

正则表达式解决方案:

import re
if re.findall('|'.join('{}\{}'.format(stringText, i) for i in endChars), textBlock):
   #condition met
   pass

您应该将any()作为最外层的操作来执行(实际上,您甚至不需要regex)。你知道吗

if any(stringText + end in textBlock for end in endChars):
    print("Match")

要执行不区分大小写的匹配,只需在两侧使用.lower()函数:

if any((stringText + end).lower() in textBlock.lower() for end in endChars):
    print("Match")

使用any()map内置的解决方案:

stringText = "something"
endChars = [",", ".", ";", " "]
textBlock = "This string may contain something;"

if any(map(textBlock.endswith, [stringText, *endChars])):
    print("Match")
  • [stringText, *endChars]是所有可能结局的list。你知道吗
  • map()将该列表的每个元素映射到方法textBlock.endswith()
  • any()返回Truemap()的任何元素True

相关问题 更多 >