I was trying to match the last number in a string, such as "34" in
3.1 General definitions 34
I am using Python-style regex, and I have tried:
(.*?)(\d)
so that later I can use \1 to refer "3.1 General definitions " and \2 to refer "34".
But \2 matches "4" instead of "34". 开发者_JAVA百科So how shall I do?
Thanks and regards!
You're currently only matching a single digit. Try
(.*?)(\d+)
to match at least one digit. This should be all you need, as you've already made the first part of the match reluctant (non-greedy).
Depending on how you're performing the match, you may need an "end of string" anchor ($) at the end, to make sure it doesn't match the digits at the start of the string.
Your original approach:
>>> re.match(r'(.*?)(\d)', '3.1 General definitions 34').groups()
('', '3')
Jon Skeet's answer (edit: I forgot to inculde Jon's suggestion to anchor to end of string, example is now corrected):
>>> re.match(r'(.*?)(\d+$)', '3.1 General definitions 34').groups()
('3.1 General definitions ', '34')
What I think is correct: new: If the string doesn't end with a number, I would do it this way:
>>> re.match(r'(.*)(?<=\D)(\d+)', '3.1 General definitions 34 more text').groups()
('3.1 General definitions ', '34')
.*
needs to be greedy to get the beginning of the string that you wanted, but we can't have it slurp up the first digit of 34
so we provide (?<=\D)
, a lookbehind assertion, to stop it from happening
You could try:
(.+?)(\d+$)
as it will giive you:
>>> r.groups()
(u'3.1 General definitions ', u'34')
You need to make it greedy at the begining.
精彩评论