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 – Conditional based on first part of text

Is it possible to make a conditional that does not check part of the string when is not needed?

For example:

Regex:
^[a-zA-Z]+.*#[0-9]+$

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

Example text:
feature: My name is Oliver #9123

I would like to when the text being:

release: My name is oliver

The same Regex matches both cases not requiring the #9123 for the release prefix, is that possible?

I have tried to use some regex conditionals that I found on google, but didn’t have success.

>Solution :

You could try a logical OR (|) in the regexp:

const tests=["My name is Oliver #9123",
             "release: My name is oliver",
             "this should fail",
             "#12345 another fail"];

tests.forEach(str=>
  console.log(str+" - "+(str.match(/^release|[a-zA-Z]+.*#[0-9]+/)?"pass":"fail"))
)
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