python - 正则表达式解析字符串中的百分比

标签 python regex percentage

<分区>

我想从上面的带小数点或不带小数点的字符串中获取所有百分比。 我也想得到 % 符号。

string  = """Bachelor of Engineering in Electronics from  in 2013 with 60%.
Diploma (Electronics & Video Engineering) from  in 2009 with 79.39%.
SSC from  in 2006 with 61.71%."""

我试过如下

re.findall(r'\d+%|([0-9]\d?)\.\d+%', string)

获取输出为

['', '79', '61']

但我想要如下输出

    ['60%', '79.39%', '61.71%']

任何人都可以说出我哪里出错了,并使用正则表达式来获得预期的输出。

最佳答案

您可以使用正则表达式 (\d+(\.\d+)?%)

  • \d+ 捕获 1 个或多个数字

  • (\.\d+)? 捕获一个点和 1 个或多个数字 01

  • % 按字面意思捕获 %

Demo.

关于python - 正则表达式解析字符串中的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49361612/

相关文章:

html - Colspan Bug 同时使用百分比和数字时

javascript - 正则表达式 - 捕获标记的模板文字

php - 具有双重否定匹配的正则表达式

JavaScript、正则表达式、反向匹配

python - Django RF 可写嵌套序列化器

java - 计算百分比

html - 可扩展的 DIV 取决于视口(viewport)

python - 如何在 python 中使用 .endswith 函数测试多个条件

python - Aiohttp 日志记录 : how to distinguish log messages of different requests?

python - 在 python 工作流中调整 Postgresql 性能和内存使用