Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex pattern immediately followed by another String

In the following input string

abcd, of regex is not my cup of tea and coffee , but abcd – and efgh of JS are my whisky

I want to match abcd - and only.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

More generally ab.*? followed by any number of special characters and spaces which then followed with literal and

I tried the following pattern abc.*?(?!(\w))\sand but this is matching both strings highlighted bold in the input string.

>Solution :

The pattern abc.*?(?!(\w))\sand matches too much, as .*? can backtrack (it matches any character) till this assertion (?!(\w)) it true and it can match \sand

But it is the same as writing abc.*?\sand because this part is always true (?!(\w))\s because the next character is \s and therefore automatically not \w


You could use:

\bab\w*\W*\sand\b

The pattern matches:

  • \b A word boundary to prevent a partial word match
  • ab Match literally
  • \w* Match optional word chars
  • \W* Match optional non word chars
  • \sand Match a whitespace char followed by and
  • \b A word boundary

Regex demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading