Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match last number in a string

Tags:

string

regex

I need to extract the last number that is inside a string. I'm trying to do this with regex and negative lookaheads, but it's not working. This is the regex that I have:

\d+(?!\d+) 

And these are some strings, just to give you an idea, and what the regex should match:

ARRAY[123]         matches 123  ARRAY[123].ITEM[4] matches 4 B:1000             matches 1000 B:1000.10          matches 10 

And so on. The regex matches the numbers, but all of them. I don't get why the negative lookahead is not working. Any one care to explain?

like image 862
korbes Avatar asked Mar 16 '11 02:03

korbes


People also ask

How do you match the end of a string?

End of String or Line: $ The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions. Multiline option, the match can also occur at the end of a line.

How do I match a number in regex?

To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).


1 Answers

Your regex \d+(?!\d+) says

match any number if it is not immediately followed by a number.

which is incorrect. A number is last if it is not followed (following it anywhere, not just immediately) by any other number.

When translated to regex we have:

(\d+)(?!.*\d) 

Rubular Link

like image 149
codaddict Avatar answered Sep 20 '22 22:09

codaddict