繁体   English   中英

获取正则表达式模式以仅匹配具有至少 2 个小数点的数字 python

[英]Get regex pattern to match only digits with at least 2 decimal points python

我正在尝试在 python 中使用惰性正则表达式模式来获取指定单词之后的第一个数字,在本例中为非 GAAP。 但是我只想要至少有 2 位或更多小数位的数字。

这是我的字符串:

s = 'Non-GAAP-2 net income of  with EPS of 1.21, up 23% from the fourth quarter of 2020.'

我的模式是:

\bNon.*GAAP\b.*?\b(\d+(?:\.\d+)?)\b

这与非 GAAP 之后的数字 2 匹配,而实际上我想要数字 1.21。

我该如何解决这种模式,你能解释一下逻辑吗?

谢谢。

编辑

如果我想编辑它以便我可以选择任何单词来输入指定的字符串,我将如何更改它,因为使用r文字字符串失败,并且由于 {2,} 的格式化字符串也是如此。

例如

s = f'\b{adjusted}\b.*?\b(\d+\.\d\{2,\})\b'

我试图退格这些字符,但这也失败了。

你可能需要:

\bNon-GAAP\b.*?\b(\d+\.\d{2,})\b

查看在线演示


  • \bNon-GAAP\b - 字边界之间的文字字符串“Non-GAAP”;
  • .*? - 除换行符以外的 0+(懒惰)字符;
  • \b(\d+\.\d{2,})\b - 1 个以上数字的捕获组,后跟一个文字点和至少两个数字,位于单词边界之间。

re.findall()一起使用

import re
s = 'Non-GAAP-2 net income of  with EPS of 1.21, up 23% from the fourth quarter of 2020.'
print(float(re.findall(r'\bNon-GAAP\b.*?\b(\d+\.\d{2,})\b', s)[0]))

印刷:

1.21

编辑:

将变量与 f 字符串组合:

import re
s = 'Non-GAAP-2 net income of  with EPS of 1.21, up 23% from the fourth quarter of 2020.'
adjusted = 'Non-GAAP'
print(float(re.findall(fr'\b{adjusted}\b.*?\b(\d+\.\d{{2,}})\b', s)[0]))

你原来的正则表达式几乎是正确的,只有与小数匹配的部分应该更新一下:

\bNon.*GAAP\b.*?\b(\d+\.\d{2})\b
  • Non.*GAAP :原始捕获组
  • .*? 0+ 个字符
  • (\d+\.\d{2})匹配 1+ 个小数、一个文字点,然后正好匹配 2 个小数

在此处查看演示。

您还可以使用非捕获组实现相同的结果:

(?:Non-GAAP.*)(\d+\.\d{2})
  • (?:Non-GAAP.*) :非捕获组,不包括文字字符串 'Non-GAAP' 和 0+ 个字符
  • (\d+\.\d{2,}) :捕获组以捕获 1+ 个小数、一个文字点,然后正好是 2 个小数

在此处查看演示。


更新:对于更新的问题

要使搜索字符串变量,您可以像构建字符串一样构建正则表达式:

import re;

s = 'Non-GAAP-2 net income of  with EPS of 1.21, up 23% from the fourth quarter of 2020.';

search = 'Non-GAAP';

regex = r"(?:" + search + ".*)(\d+\.\d{2})";

print(float(re.findall(regex, s)[0]));

在此处查看演示 repl.it。

为此使用 re

import re
s = 'Non-GAAP-2 net income of  with EPS of 1.21, up 23% from the fourth quarter of 2020.'

output  = re.sub(r'\d+\.\d+', '', s)

您可以使用\d*\.\d*它将捕获字符串中带小数位的第一个数字

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM