python - 正则表达式 - 在符号后查找数字
问题描述
我正在尝试使用下面的正则表达式来查找“|”之后的任何数字 运算符来处理下面的一些示例字符串。问题在于默认的正则表达式,我似乎无法将 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
'''
任何帮助表示赞赏!
解决方案
re.X
您的主要问题是您正在引入即使在使用或re.VERBOSE
标志时也不应该出现的空间。您不能将构成后视构造的字符分开。您还应该使用量化的子模式保留量词。
此外,您不需要在这里查看,只需使用捕获组捕获您的号码,然后使用match.group(1)
.
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_regex
在numeric_regex
我们可能想要重用的 中,使用了一个非捕获组,(?:...)
因为我们需要的只是在这里对两个备选方案进行分组。
现在主要的正则表达式方案是.*\|.*?({numeric_regex})$
,即|
尽可能少地匹配除换行符之外的 0 个或多个字符,然后将数字部分捕获到第 1 组中,然后$
断言字符串末尾的位置。由于第一个.*
,您将获得最右边的|
(和后续模式)匹配。
推荐阅读
- linq - Linq 加入 2 个表并为这两个表使用 contains
- c++ - Qt Creator 无法启动 cdb 调试器
- html - TYPO3 name of language file?
- java - 如何整体导出依赖项?
- mongodb - 在 Redash 中更新 Mongo 文档的查询
- amazon-web-services - 安装 Boto3 AWS EMR 尝试下载引导操作失败
- prolog - Prolog中解决农民山羊狼和白菜问题的优化
- php - PHP 不会通过 POST 传递变量
- android - 在 Delphi 上更改导航栏颜色
- javascript - 链接在 React 组件中获取“POST”