簡體   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