首页 > 解决方案 > 正则表达式 - 在符号后查找数字

问题描述

我正在尝试使用下面的正则表达式来查找“|”之后的任何数字 运算符来处理下面的一些示例字符串。问题在于默认的正则表达式,我似乎无法将 numeric_regex 与 Lookbehind 结合起来。

'xxx -> 31223.1 | xxx -> 1.1'.    to get 1.1

'0 | 1'     to get 1

numeric_regex = ''' 
                [-+]?                    # pos or neg
                (?: (?: \d* \. \d+ ) |   # float (ie .1 and 1.1)
                (?: \d+ \.? ) )          # int (with trailing periods ie 1.)
            '''

default_regex = f'''
                (? <= \|).               # after but not including |
                {numeric_regex}          # all digits
                + $                      # end of the string
            '''

任何帮助表示赞赏!

标签: pythonregex

解决方案


re.X您的主要问题是您正在引入即使在使用或re.VERBOSE标志时也不应该出现的空间。您不能将构成后视构造的字符分开。您还应该使用量化的子模式保留量词。

此外,您不需要在这里查看,只需使用捕获组捕获您的号码,然后使用match.group(1).

查看完整的 Python 演示正则表达式演示

import re
numeric_regex = r'''
                [-+]?                    # pos or neg
                (?:
                  \d*\.\d+               # float (ie .1 and 1.1)
                  | 
                  \d+ \.?                # int (with trailing periods ie 1.)
                )'''

default_regex = rf'''
                .*                       # Match as many chars as possible (use with re.S)
                \|.*?                    #  | and 0+ chars as few as possible
                ({numeric_regex})        # Capturing group: all digits
                $                        # end of the string
'''
m = re.search(default_regex, "xxx -> 31223.1 | xxx 1.1", re.S | re.VERBOSE)
if m:
    print(m.group(1)) # => 1.1

请注意(...). default_regexnumeric_regex我们可能想要重用的 中,使用了一个非捕获组,(?:...)因为我们需要的只是在这里对两个备选方案进行分组。

现在主要的正则表达式方案是.*\|.*?({numeric_regex})$,即|尽可能少地匹配除换行符之外的 0 个或多个字符,然后将数字部分捕获到第 1 组中,然后$断言字符串末尾的位置。由于第一个.*,您将获得最右边的|(和后续模式)匹配。


推荐阅读