簡體   English   中英

在字符串中搜索子字符串的潛在組合

[英]Searching string for potential combinations of substrings

我有一個string ,一個array ,其中包含該字符串的可能結尾字符,以及要解析的文本塊。 例如:

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

if語句的一行中,我想檢查textBlock包含stringText后跟任意endChars 我很確定我可以使用Python 2.7中的any內置函數來做到這一點,但是到目前為止我的努力都失敗了。 我有類似的東西:

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

我看過這篇文章,但是我正在努力將其應用到上面的支票中。 這樣做的任何幫助將不勝感激。

編輯:

除了上述內容之外,還可以確定在字符串中找到了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 ;

實際輸出 NameError: name 'end' is not defined

更新我已經找到了解決此問題的合適方法,至少出於我的要求。 它不是單線的,但可以完成任務。 為了完整性,如下所示

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

您應該執行any()作為最重要的操作(實際上,您甚至不需要正則表達式)。

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")

非正則表達式解決方案:

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()和內置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
testBlock.endswith(tuple([stringText + endChar for endChar in endChars]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM