Python使用正则表达式从文本中提取数字

时间:2016-04-18 03:38:56

标签: python regex

我有一个这样的字符串:

var hours_tdate = ['22','23','<span style="color:#1d953f;">0</span>','<span style="color:#1d953f;">1</span>'];

这是js文件的一部分。现在我想使用正则表达式从上面的字符串中提取数字,并输出如下:

[22,23,0,1]

我试过了:

re.findall('var hours_tdate = \[(.*)\];', string)

它给了我:

'22','23','<span style="color:#1d953f;">0</span>','<span style="color:#1d953f;">1</span>'

当我尝试时,我不知道为什么它不匹配:

re.findall('var hours_tdate = \[(\d*)\];', string)

2 个答案:

答案 0 :(得分:1)

使用\d+和字边界仅提取数字

\b\d+\b

<强> Regex Demo

Python代码

p = re.compile(r'\b\d+\b')
test_str = "var hours_tdate = ['22','23','<span style=\"color:#1d953f;\">0</span>','<span style=\"color:#1d953f;\">1</span>'];"

print(re.findall(p, test_str))

<强> Ideone Demo

注意: - 即使变量名中有数字,只要您的变量格式正确,它就不重要了

答案 1 :(得分:0)

提供另一个例子:

['>](\d+)['<]
# one of ' or >
# followed by digits
# followed by one of ' or <

Python代码中:

import re
rx = r"['>](\d+)['<]"
matches = [match.group(1) for match in re.finditer(rx, string)]

或使用 lookarounds 仅匹配您想要的内容(不需要其他群组):

(?<=[>'])\d+(?=[<'])

再次,在Python代码中:

import re
rx = r"(?<=[>'])\d+(?=[<'])"
matches = re.findall(rx, string)
相关问题