我有一个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)
非正则表达式解决方案:
正则表达式解决方案:
您应该将
any()
作为最外层的操作来执行(实际上,您甚至不需要regex)。你知道吗要执行不区分大小写的匹配,只需在两侧使用
.lower()
函数:使用
any()
和map
内置的解决方案:[stringText, *endChars]
是所有可能结局的list
。你知道吗map()
将该列表的每个元素映射到方法textBlock.endswith()
any()
返回True
是map()
的任何元素True
相关问题 更多 >
编程相关推荐