python - 存在一些顺序无关紧要的单词的正则表达式

标签 python regex string string-matching regex-lookarounds

我想编写一个正则表达式来搜索某些单词的存在,但它们出现的顺序无关紧要。

例如,搜索“Tim”和“stupid”。我的正则表达式是 Tim.*stupid|stupid.*Tim。但是是否可以编写一个更简单的正则表达式(例如,这两个词在正则表达式本身中只出现一次)?

最佳答案

看这个正则表达式:

/^(?=.*Tim)(?=.*stupid).+/

正则表达式解释:

  • ^断言字符串开头的位置。
  • (?=.*Tim)断言字符串中存在“Tim”。
  • (?=.*stupid)断言字符串中存在“stupid”。
  • .+现在我们的短语已经存在,这个字符串是有效的。继续使用 .+或 - .++匹配整个字符串。

要更专门地使用前瞻,您可以添加另一个 (?=.*<to_assert>)团体。整个正则表达式可以简化为 /^(?=.*Tim).*stupid/ .

参见 a regex demo !

>>> import re
>>> str ="""
... Tim is so stupid.
... stupid Tim!
... Tim foobar barfoo.
... Where is Tim?"""
>>> m = re.findall(r'^(?=.*Tim)(?=.*stupid).+$', str, re.MULTILINE)
>>> m
['Tim is so stupid.', 'stupid Tim!']
>>> m = re.findall(r'^(?=.*Tim).*stupid', str, re.MULTILINE)
>>> m
['Tim is so stupid.', 'stupid Tim!']

阅读更多:

关于python - 存在一些顺序无关紧要的单词的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24656131/

相关文章:

python - 按特定顺序对文件进行排序

python - 方法重载装饰器

regex - 如何使用 shell 脚本查找 Linux 发行版名称?

c# - 字符串属性是否可以具有函数?

python - 写入 csv 文件时如何格式化 pandas 数据框?

python - 在 Python 中解码一列 Base64 字符串

c++ - 同时使用 std::regex,定义的行为?

python - 正则表达式:替换所有数字和 "number-like"字符串(范围内的年份除外)

C++读取数字字符串并将特定位置字符捕获为int

c++ - 将 uint8 转换为字符串