Home > Back-end >  Regular Expression to match a sentence which induces a word with specific suffix and defined end wor
Regular Expression to match a sentence which induces a word with specific suffix and defined end wor

Time:12-22

I'm trying to match a sentence which includes a word with a certain suffix and a specific word at the end.
For example sentence template would be;
"word word word (doesn't matter how many words before) wordSUFFIX thatspecificword."

I have tried this but could not match the words in the beginning.

(\w )(SUFFIX)\s thatspEcificword(suffix)?

CodePudding user response:

This should work:

Regex

.*(\b.*SUFFIX\b).*(specificword)$

See demo

Explanation

  • .* - search for zero or more characters of any type
  • (\b.*SUFFIX\b) - search for a word ending with SUFFIX
  • (specificword)$ - search for a "specificword" at the end of sentence.

Note:

If you cannot have matches where the entire word is SUFFIX, then you will need to change the regex to:

.*(\b. SUFFIX\b).*(specificword)$

The . ensures that there is at least one character before the SUFFIX

CodePudding user response:

As question tags are related to python, will try to answer from pythonic view.

If you simply want string ending with SUFFIX thatspecificword, then you may simply code like below -

pattern = "SUFFIX thatspecificword"
s = "word word word (doesn't matter how many words before) wordSUFFIX thatspecificword"
if s.endswith(pattern):
    print("match found")
else:
    print("match not found")

But if you want the string ending with wordSUFFIX thatspecificword where word can be any word i.e SUFFIX must be a word suffix then you might have a look into python built-in package named re which deals with regular expression -

import re

pattern = "\wSUFFIX thatspecificword$"
s = "word word word (doesn't matter how many words before) wordSUFFIX thatspecificword"
if re.search(pattern, s):
    print("match found")
else:
    print("match not found")
  • Related