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 don't match specific string

I have a regex, for simplicity let’s say it’s:

([a-z]*[0-9])

For the string aa bbc1 cc it matches bbc1.

Now I want to change the regex in such a way that c1 is not part of the match anymore. But only if it’s c1.

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

Some examples:
aa bbb1 cc will match bbb1
aa bbc1 cc will match bb
aa bbc2 cc will match bbc2

What I tried:
Negative lookbehind:

([a-z]*[0-9])(?<!c1)

will not provide bb anymore with aa bbc1 cc

Negative lookforward:

(?!c1)([a-z]*[0-9])

Does not seem to make a difference

I’m using javascript.

>Solution :

You may use this regex:

\b[a-z]*?(?:(?=c1)|\d)

RegEx Demo

RegEx Details:

  • \b: Word boundary
  • [a-z]*?: Match 0 or more lowercase letters. Match is non-greedy (lazy) due to use of *?
  • (?:: Start a non-capture group
    • (?=c1): Lookahead to assert that we have c1 immediately ahead of the current position
    • |: OR
    • \d: Match a digit
  • ): End non-capture group

PS: If you want your words to end with these combinations then I would suggest:

\b[a-z]*?(?:(?=c1\b)|\d\b)
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