[英]Adjust Python Regex to not include a single digit in the findall results
我試圖從一些字符串中捕獲/提取數值。
這是一個示例字符串:
s='The shipping company had 93,999,888.5685 gallons of fuel on hand'
我想把我的正則表達式的93,999,888.5685值拉到此
> mine=re.compile("(\d{1,3}([,\d{3}])*[.\d+]*)")
但是,當我做一個findall我得到以下內容:
mine.findall(s)
[('93,999,888.5685', '8')]
我已經嘗試了許多不同的策略來防止它在8上匹配
但我現在意識到我不知道為什么它與8匹配
任何照明將不勝感激。
捕獲8的原因是因為您有2個捕獲組。 使用?:
將第二組標記為非捕獲組?:
使用此模式: (\\d{1,3}(?:[,\\d{3}])*[.\\d+]*)
你的第二組([,\\d{3}])
負責額外的比賽。
你的字符串分解了:
(
\d{1,3} This will match any group of 1-3 digits (`8`, `12`, `000`, etc)
(
[,\d{3}] This will match groups of a "," and 3 digits (`,123`, `,000`, etc)
)* **from zero to infinity times**
[.\d+]* This matches any number of periods "." and digits from 0 to infinity
)
findall
為每個匹配返回一個元組。 元組包含匹配的每個組(由正則表達式中的括號描繪)。 你只想要第一組。 下面我使用了列表理解來拉出第一組。
>>> mine=re.compile("(\d{1,3}(,\d{3})*(\.?\d+)*)")
>>> s='blah 93,999,888.5685 blah blah blah 988,122.3.'
>>> [m[0] for m in mine.findall(s)]
['93,999,888.5685', '988,122.3']
為什么不將它包裝在\\ D? mine=re.compile("\\D(\\d{1,3}([,\\d{3}]) [.\\d+] )\\D")
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.