匹配字符串中最后一个数字的正则表达式 [英] Regular expression to match last number in a string
问题描述
我需要提取字符串中的最后一个数字.我正在尝试使用正则表达式和负前瞻来做到这一点,但它不起作用.这是我拥有的正则表达式:
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?
推荐答案
你的正则表达式 \d+(?!\d+)
说
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)
这篇关于匹配字符串中最后一个数字的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!