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
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