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



我想知道字符串"厨师;但按顺序排列在另一个长度>1.
因此,基本上我们希望字符串ch、he、ef、che、hefchefbr/>例如:
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')

P.S.很抱歉,如果这个问题已经被问到并解决了,我找不到它。
谢谢

纯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

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

最新更新