簡體   English   中英

用於數字集和關鍵字的Python正則表達式

[英]Python regular expression for number set and key word

我正在嘗試使用re來找到一種模式,以找到一個數字序列,然后是一些關鍵詞。

string =" 12390 total income stated in red followed by 567 total income stated in blue."
pattern = re.match("\s*\d{1,2}\s* total income",string)

我嘗試過這種模式 ,但是效果不好。 我希望最后得到以下結果:“ 12390總收入”和“ 567總收入”。

您需要使用re.findall並將模式\\d{1,2}更改為\\d+一個或多個數字字符 ),因為\\d{1,2}應該只匹配最小1位數和最大2位數。

result = re.findall(r"\d+ total income",string)

請注意, match嘗試從字符串的findall進行匹配,其中findall應該進行全局匹配。

如果在這種情況下, 數字總收入之間有幾個空格(例如1或2等),請使用非捕獲組構造

說的字符串是

string = '12390total income stated in red followed by 567      total income stated in blue.'

然后嘗試如下

myresult = re.findall(r"\d+(?:\s*?total income)",string)

提取物

['12390total income', '567      total income']

然后使用replace刪除多余的空間。

enter code here

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM