Which regex would fit better to extract the last 2 numbers separated by dot
e.g.
abc.98.76.xyz12.34 -> 12.34
qwer12.34.ty.98.76 -> 98.76
I tried \d (?!\d )\.\d (?!\d )$
but not sure if it's the best option.
CodePudding user response:
Possible solution is the following:
(\d \.\d )$
See explanation at regex101
if you need to specify exact qty of numbers:
(\d{2}\.\d{2})$
Where:
\d - any digit
- one o more characters
\. - dot
{2} - exactly two characters
$ - end of string
CodePudding user response:
Here are two ways to do that.
If the string matches
.*(?<!\d)(\d \.\d )
the desired result will be held by capture group 1.
.*
is greedy, so it will consume as many characters as possible, including digits and periods. The negative lookbehind (?<!\d)
ensures that the last character matched by .*
is not a digit. Without it, for the string 'abc12.34'
, .*
would match 'abc1
' and capture group 1 would contain '2.34'
.
The other option is to match the regular expression
\d \.\d (?!.*\d \.\d )
which does not use a capture group.
The negative lookahead (?!.*\d \.\d )
ensures that the match is not followed by another instance of one or more digits followed by a period followed by one or more digits.