简体   繁体   English

正则表达式Python在单个表达式中提取两个字符串之间的数字

[英]Regex Python extract digits between two strings in a single expression

I want only digits existing between two characters in order to get an integer dollar value, eg from string: 我只想在两个字符之间存在数字以获得整数美元值,例如来自字符串:

"Advance [Extra Value of $1,730,555] in packages 2,3, and 5."

we want to obtain "1730555" . 我们想获得"1730555"

We can use \\$(.*)\\] to get "1,730,555" , but how do we remove the commas in the same expression, while retaining the possibility of arbitrary many commas, ideally getting the number in a single capturing group? 我们可以使用\\$(.*)\\]来获取"1,730,555" ,但是我们如何删除同一个表达式中的逗号,同时保留任意多个逗号的可能性,理想情况下在单个捕获组中获取数字?

You can try like this 你可以这样试试

import re
text = "Advance [Extra Value of $1,730,555] in packages 2,3, and 5."
match = re.findall(r'\$(.*)]',text)[0].replace(',','')
print match

You could use split and join: 您可以使用拆分和连接:

import re

s = "Advance [Extra Value of $1,730,555] in packages 2,3, and 5."

match = re.findall(r'\$([\d,]+)', s)
number = ''.join(match[0].split(','))
print(number)

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

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