正则表达式最后出现带负号的模式

时间:2020-07-18 03:22:45

标签: python-3.x regex

我一直在Regex上关注Freecodecamp's tutorial,以便能够获得我打算获取的模式的最后一次出现。我打算获取数字(带/不带负号),数字以及其后的任何字符

目标:

    aa-11aa -> gets the -11aa
    11aa -> gets the 11aa
    aa11aa11aa -> gets the 2nd 11aa
    aa-11aa-11aa -> gets the 2nd -11aa
    aa-11a(a) -> gets the -11a(a)

但是,我只能使这种模式起作用,以便只得到一个数字,然后对数字后面的内容进行修正。 (?:.*)(-*\d+)(.*)$。这些是我的模式的结果:

问题:

    aa-11aa -> gets the 1aa
    11aa -> gets the 1aa
    aa11aa11aa -> get the 2nd 1aa
    aa-11aa-11aa -> get the 2nd 1aa
    aa-11a(a) -> gets the 1a(a)

任何有关如何获得期望结果的帮助吗?

2 个答案:

答案 0 :(得分:1)

尝试一下:

-?\d+[^\d]+$

它也包括第二位数字,因为.表示任何字符。

请注意, \w匹配任何单词字符(等于[a-zA-Z0-9_]

答案 1 :(得分:1)

以下应该可以工作

.*?(-?\d+[^\d]*)$

首先非贪婪地匹配任何前面的字符,然后在您的组中有条件地匹配减号,后跟一些数字,然后是零个或多个不是数字的字符