Reputation: 103
I'm trying to get the right syntax for getting the number of matches from list of words example:
List: (US,UK,Greece,Germany,Nigeria,Brazil)
The text is: "Cake returns put Brazil Welcome Stack to between paragraphs Argentina Overflow UK"
I would like to know how many words from the list above appear in this text with a regex pattern. Alternative, I would like to know if there more than 1 match from the list in the text
Is it possible to do that with Regex?
Upvotes: 2
Views: 1367
Reputation: 336478
In Python:
>>> import re
>>> countries = re.compile(r"\b(?:US|UK|Greece|Germany|Nigeria|Brazil)\b")
>>> text = "Cake returns put Brazil Welcome Stack to between paragraphs Argentina Overflow UK"
>>> len(countries.findall(text))
2
Explanation:
\b # Word boundary (start of word)
(?: # Match either...
US # US
| # or
UK # UK
| # or
Greece # Greece (etc.)
) # End of alternation
\b # Word boundary (end of word)
Upvotes: 2