需要从字符串中提取值,值可以包含逗号,小数点,逗号和小数点,不带逗号和小数点,带逗号和小数。
例如:
1,921.15
921.15
921
1,921
re.findall(r'[-+]?\d+[,.]?\d*',st)[3]" its extracting only 1,921 but not as 1,921.15
st='["FL gr_20 PT10 MT3\'><strong>1,921.15</strong>"]'
我试过 re.findall(r'[-+]?\d+[,.]?\d*',st)[3] 它只提取 1,921 但不是 1,921.15
从字符串 st 下面,使用 re 模块,我需要提取值 1,921.15
st='["FL gr_20 PT10 MT3\'><strong>1,921.15</strong>"]'
Expected = 1,921.15
Actual = 1,921
请您参考如下方法:
一般,当你想使用 Python 正则表达式从文本中提取正整数或负整数或 float 时,你可以使用以下模式
re.findall(r'[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?', text)
参见 this regex demo . 注意:\d{1,3}(?:,\d{3})+ alternative 匹配以逗号作为千位分隔符的整数。您可以调整它以匹配您需要的千位分隔符,例如 \xA0如果千位分隔符是不间断空格,或者 \.如果是点等
更多选项看起来像
re.findall(r'[-+]?\d+(?:\.\d+)?', text) # Integer part is compulsory, e.g. 5.55
re.findall(r'[-+]?\d*\.?\d+', text) # Also matches .57 or -.76
在这里,您想提取 > 之间的任意数字和 <字符。
你可以使用
re.findall(r'>([-+]?\d[\d,.]*)<', text)
参见 regex demo .
详情
-
>- 一个>字符 -
([-+]?\d[\d,.]*)- 第 1 组:-
[-+]?- 一个可选的-或+ -
\d- 一个数字 -
[\d,.]*- 0 个或多个数字,,或.
-
参见 Python demo :
import re
st='''["FL gr_20 T3\'><strong>+1,921.15</strong>"]' st='["FL gr_20 T3\'><strong>-921.15</strong>"]' st='["FL gr_20 T3\'><strong>21.15</strong>"]' st='["FL gr_20 T3\'><strong>1,11,921.15</strong>"]' st='["FL gr_20 T3\'><strong>1,921</strong>"]' st='["FL gr_20 T3\'><strong>112921</strong>"]' st='["FL gr_20 T3\'><strong>1.15</strong>"]' st='["FL gr_20 T3\'><strong>1</strong>"]'''
print(re.findall(r'>([-+]?\d[\d,.]*)<', st))
# => ['+1,921.15', '-921.15', '21.15', '1,11,921.15', '1,921', '112921', '1.15', '1']
