使用python正则表达式在文本中查找特定的patern

时间:2018-04-29 15:04:00

标签: python regex

我的字符串是

'21,300 32,709 30,391 29,901 22,270 31,201 31,199 27,806 23,210 28,418 28,940 32,496 16.9%'

我怎样才能找到所有数字但是16.9%??

我用过

pattern = re.compile(r'\d+,*\d*(?!%)')

但这不起作用。

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以将re.findall与这些模式示例一起使用:

import re

a = '21,300 32,709 30,391 29,901 22,270 31,201 31,199 27,806 23,210 28,418 28,940 32,496 16.9%'

final = re.findall(r'(\d+)[,\s]', a)
# Or:
# final = re.findall(r'(\d+)[^\d\.%]', a)

两者都会输出:

print(final)

['21', '300', '32', '709', '30', '391', '29', '901', '22', '270', '31', '201', '31', '199', '27', '806', '23', '210', '28', '418', '28', '940', '32', '496']

答案 1 :(得分:-2)

import re

a = '21,300 32,709 30,391 29,901 22,270 31,201 31,199 27,806 23,210 28,418 28,940 32,496 16.9%'

re.findall(r'\d+.\d+%', a)

此正则表达式将捕获您想要的百分比。基本上,我用“'%'带有一个或多个数字,用点分隔。'