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 if character matches then, else

I have two regular expressions that work fine to extract text between characters:

  1. (?<=\$)(.*)(?=\*)
  2. (?<=\$)(.*)(?=)

For my example text $66* the first expression extracts 66. When the asterisk is not present in the text (i.e. $66), the second expression extracts 66.

How can I combine the two to use the first one if an asterisk is present and the second one if no asterisk is present?

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

I tried with what I thought would be an if|then|else like below but am doing something wrong: (?(?=\*)(?<=\$)(.*)(?=\*)|(?<=\$)(.*)(?=))

>Solution :

You can use a negated character set to exclude asterisks in your match instead:

(?<=\$)[^*]+

Demo: https://regex101.com/r/vuGBiJ/2

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