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

Regular expression to get specific numbers from a string with a condition

I wish to extract “2” (00000002)the from below string. But the condition is that the string should start with *X1. I wish to have a generic regular expression as in if there will any number it should return it.

*X19845674367       00000002+000000000000123000KGS000CDH000002

I have tried this regex –

(?<=\d)([1-9])\d*(?=\+)

But it returns number all the strings,
But I wish have from a specific tag e.g. *X1

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

Any suggestions would be helpful. Thanks.

>Solution :

If you don’t want to use capturing groups, then another valid expression is this one:

(?<=\*[^\s]+\s+0*)([1-9]+[0-9]*)(?=\+)

Instead of ([1-9]+[0-9]*), creating a capturing group, you can also leave out the brackets – [1-9]+[0-9]*, works either way.

The expression allows for anything in front, then some spaces, then capturing the first number, but ignoring 0 prefixes.

You can play around with it and look at the in-depth explainations using the demo here:
https://regex101.com/r/gyMx2i/1

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