Skip to main content
 首页 » 编程设计

Python如何匹配略有不同的字符串中的子字符串

2025年02月15日23hnrainll

我有以下问题,但找不到解决方案。

我必须找到以下子字符串的确切开始和结束位置:

"hello world is a good idea for a T-shirt" 

在任何可能的其他字符串中,例如:

"This is some string, that includes commas, and other punctuations. It also includes hello world, is a, good, idea for a T-shirt and other." 

由于标点符号(逗号),find() 不会给我结果。我正在尝试使用正则表达式,例如 r"(Hello)[\W+] (world) [\W+]..." 但它也不起作用。有什么好的想法吗?

编辑:

这是我的代码:

import re 
text = "This is some string, that includes commas, and other punctuations. It also includes hello world, is a, good, idea for a T-shirt and other." 
match = re.search(r"[\W+](hello)[\W+](world)[\W+](is)[\W+](a)[\W+](good)[\W+](idea)[\W+](for)[\W+](a)[\W+](T-shirt)", text) 
print (match) 

请您参考如下方法:

当您使用 [\W+] 时,您创建了一个匹配单个字符的字符类,该字符可以是非单词字符(任何不是字母的字符, 数字或 _) 或文字 + 符号。

使用\W+代替空格:

import re 
text = "This is some string, that includes commas, and other punctuations. It also includes hello world, is a, good, idea for a T-shirt and other." 
match = re.search(r"hello\W+world\W+is\W+a\W+good\W+idea\W+for\W+a\W+T-shirt", text) 
if match: 
    print("YES!") 

参见 Python demo

\W 匹配任何不是字母、数字或 _ 字符的字符,+ 使正则表达式引擎匹配 1 个或多个这些字符的出现。

为了使代码更通用,您可以用空格分隔初始字符串,然后用正则表达式模式连接以匹配空格或逗号或点。

import re 
key = "hello world is a good idea for a T-shirt" 
pat = r"\W+".join([re.escape(x) for x in key.split()]) 
# print(pat) # => hello\W+world\W+is\W+a\W+good\W+idea\W+for\W+a\W+T\-shirt 
text = "This is some string, that includes commas, and other punctuations. It also includes hello world, is a, good, idea for a T-shirt and other." 
match = re.search(pat, text) 
if match: 
    print("YES!") 

参见 another Python demo