【问题标题】:Finding if common sub-string exists with regex使用正则表达式查找公共子字符串是否存在
【发布时间】:2021-09-29 23:41:50
【问题描述】:

我想查找是否存在字符串“chef”的子字符串,但在另一个长度 > 1 的给定字符串中按顺序排列。
所以基本上我们希望字符串 ch, he, ef, che, hefchef 存在于给定的字符串中。

前任:
1> kefaa
这里我们有 ef ,它是 ''chef'' 的一部分,所以它是一个有效的字符串。
2> 弗拉塞克
这里我们有 fh 哪些字符存在于 'chef' 但顺序不正确因此无效。

我有这个可以工作的代码,但是在这里手动添加子字符串很容易,因为字符串 'chef' 的可能性要少得多,但我想要一个适用于任何给定字符串的代码。

import re
pattern = r"(ch|he|ef|che|hef|chef)"
s = input()
res = re.search(pattern, s)
if bool(res):
    print('YES')
else:
    print('NO')

附言对不起,如果这个问题已经被问到并解决了,我找不到它。
谢谢。

【问题讨论】:

  • 您可以使用? 将每个字符设为可选,然后检查字符串是否为空。
  • @RyanSchaefer 但是字符串 'fhlasek' 也将被视为有效。我们不需要那个。
  • 如果你只是只想找到if有子串,那么检查长度大于2的子串是没有意义的。跨度>
  • @Armali 是的,但提到它是为了确保我们不只匹配一个普通字母。

标签: python regex string substring


【解决方案1】:

纯 Python:

def test(txt, string):
    le = len(txt)
    fragments = [txt[i:j] for i in range(le) for j in range(i+1, le+1) if j-i>1]
    # 'chef' --> ['ch', 'che', 'chef', 'he', 'hef', 'ef']

    for fragment in fragments: 
        if fragment in string: return 'YES';
    return 'NO' 

print(test("chef", "ch"))     # YES
print(test("chef", "che"))    # YES
print(test("chef", "c"))      # NO
print(test("chef", "fh"))     # NO
print(test("chef", "kefaa"))  # YES

如果你需要正则表达式,你可以去:

import re

def get_reg(txt,s):
    le = len(txt)
    fragments = [txt[i:j] for i in range(le) for j in range(i+1, le+1) if j-i>1]
    return bool(re.search("|".join(fragments),s))
    # 'chef' --> 'ch|che|chef|he|hef|ef'

print(get_reg("chef","ch"))    # True
print(get_reg("chef","che"))   # True
print(get_reg("chef","c"))     # False
print(get_reg("chef","fh"))    # False
print(get_reg("chef","kefaa")) # True

递归:

import re

def get_framgents(word):
    for i in range(len(word)-1):
        fragments.append(word[:len(word)-i])
    if len(word)>0:
        get_framgents(word[1:])
        
word = 'chef'
fragments = []
get_framgents(word)             # --> ['chef','che','ch','hef','he','ef']
fragments = '|'.join(fragments) # --> 'chef|che|ch|hef|he|ef'

print(bool(re.search(fragments, "ch")))    # True
print(bool(re.search(fragments, "che")))   # True  
print(bool(re.search(fragments, "c")))     # False
print(bool(re.search(fragments, "fh")))    # False
print(bool(re.search(fragments, "kaeef"))) # True

【讨论】:

    【解决方案2】:

    您可以遍历单词并构建自定义正则表达式,然后在 search 中使用该正则表达式:

    from re import search, compile
    
    word = "chef"
    s = input()
    
    pattern = []
    for i in range(len(word) - 1):
        pattern.append(word[i] + word[i+1])
    pattern = compile("|".join(pattern))
    
    if bool(search(pattern, s)):
        print("Yes")
    else:
        print("No")
    

    【讨论】:

    • 但它只得到三个子字符串ch|he|ef
    • 这样想:如果一个词包含子串 hef,那么它也将包含子串 he 和 ef。另请参阅上面的Armali's comment
    猜你喜欢
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2022-01-23
    • 2016-05-16
    • 2012-05-12
    • 1970-01-01
    相关资源
    最近更新 更多