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

标签 python regex

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

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

"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

关于Python如何匹配略有不同的字符串中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45440078/

相关文章:

javascript - javascript中的replace()回调函数没有被调用

python - 正则表达式确定字符串是否以数字结尾/包含 '//'之间的数字

regex - 如何在文本中屏蔽信用卡号掩码?

android - 为 android 商店签署 kivy 应用程序时出错

python - 遍历字典列表并从列表中找到匹配的元素并将匹配键的值附加到 defaultdict

python - 使用Python进行回溯算法

Python ASCII 到二进制

c# - 如何获取字符串末尾的数字?

java - 如何避免重复加载大文件?

python - 如何在Python中将单引号替换为反斜杠+单引号