查找正则表达式中是否存在公共子字符串

2024-06-26 17:45:04 发布

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

我想知道是否存在字符串“chef”的子字符串,但在另一个给定的字符串中,该字符串的长度为>;1.
所以基本上我们希望字符串ch,he,ef,che,hefchef存在于给定的字符串中

前任:
1>;kefaa
这里我们有ef,它是“chef”的一部分,因此它是一个有效字符串
2>;fhlasek
这里我们有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')

另外,如果这个问题已经被问到并解决了,我很抱歉,我找不到它
非常感谢。

Tags: 字符串代码gtrereschechchef
2条回答

您可以循环使用word并构建自定义正则表达式,然后在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")

纯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

如果您需要regexp,请点击这里:

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

相关问题 更多 >