简体   繁体   中英

Regex check if specific multiple words present in a sentence

Is there a regex for us to check if multiple words are present in a string

Ex :

sentence = "hello i am from New York city"

I want to check if 'hello' 'from' and 'city' are present in sentence.

I have tried using

re.compile("hello|from|city")

but no luck as it returns true if even a single match is found.

You can't alternate, because then a match for any of the alternations would fulfill the regex. Instead, use multiple lookaheads from the start of the string:

sentence1 = "hello i am from New York city"
sentence2 = "hello i am from New York"
regex = re.compile(r"^(?=.*hello)(?=.*from)(?=.*city)")
print(regex.match(sentence1))
print(regex.match(sentence2))

Output:

<_sre.SRE_Match object; span=(0, 0), match=''>
None

You can use the all() built in method.

Documentation here

Effectively the function takes an iterable type as a parameter.

Example:

words = ["hello", "from", "city"]
if all(word in 'hello from the city' for word in words):
  # Do Something

You can do this without using regex, just checking entrance of each word (from words ) in sentence :

sentence = "hello i am from New York city"
words = ['hello', 'from', 'city']
all([w in sentence.split() for w in words])

In my opinion, this way is preferable because of clarity.

Try:

>>> sentence = "hello i am from New York city"
>>> def f(s):
    return all(s.split().__contains__(i) for i in ['hello','from','city'])

>>> f(sentence)
True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM