Regex for existence of some words whose order doesn't matter

*爱你&永不变心* 提交于 2019-11-26 07:42:35

问题


I would like to write a regex for searching for the existence of some words, but their order of appearance doesn\'t matter.

For example, search for \"Tim\" and \"stupid\". My regex is Tim.*stupid|stupid.*Tim. But is it possible to write a simpler regex (e.g. so that the two words appear just once in the regex itself)?


回答1:


See this regex:

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

Regex explanation:

  • ^ Asserts position at start of string.
  • (?=.*Tim) Asserts that "Tim" is present in the string.
  • (?=.*stupid) Asserts that "stupid" is present in the string.
  • .+Now that our phrases are present, this string is valid. Go ahead and use .+ or - .++ to match the entire string.

To use lookaheads more exclusively, you can add another (?=.*<to_assert>) group. The entire regex can be simplified as /^(?=.*Tim).*stupid/.

See 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!']

Read more:

  • Regex with exclusion chars and another regex



回答2:


You can use Positive Lookahead to achieve this. The lookahead approach is nice for matching strings that contain both substrings regardless of order.

pattern = re.compile(r'^(?=.*Tim)(?=.*stupid).*$')

Example:

>>> s = '''Hey there stupid, hey there Tim
Hi Tim, this is stupid
Hi Tim, this is great'''
...
>>> import re
>>> pattern = re.compile(r'^(?=.*Tim)(?=.*stupid).*$', re.M)
>>> pattern.findall(s)

# ['Hey there stupid, hey there Tim', 'Hi Tim, this is stupid']


来源:https://stackoverflow.com/questions/24656131/regex-for-existence-of-some-words-whose-order-doesnt-matter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!