英文:
Regex that matches only numbers in a percentage separated by comma or dot
问题
我使用Python,例如,我有一个字符串如下:
a good 98.15% play
应该匹配9815,
a good 98,15% play
也应该匹配9815,
a good 100% play
应该匹配100
a good 98% play
应该匹配98
我已经尝试使用(?<=\s)\S+(?=\%)
来匹配整个98.15,但是有更多的人使用逗号来分隔小数点,我尝试使用其他正则表达式,但没有任何一个能够满足我的问题。
英文:
I use python, for example, I have a string like this:
a good 98.15% play
it should match 9815,
a good 98,15% play
it should also match 9815,
a good 100% play
it should match 100
a good 98% play
it should match 98
I have tried to use (?<=\s)\S+(?=\%)
to match the whole 98.15 but there are more people using comma to separate decimal number than I thought and I tried to use other regex but there aren't any I could think of that satisfy my problem.
答案1
得分: 1
Remove the .
if it is there, and the regex to capture the numbers. I'd remove the .
first, then simply (\d+)%
In python, I think its .replace('.', '') to remove the .
英文:
Remove the .
if it is there, and the regex to capture the numbers. I'd remove the . first, then simply (\d+)%
In python, I think its .replace('.','') to remove the .
答案2
得分: 1
我已找到解决方法,我只需使用字符串替换方法将所有逗号替换为点,然后使用我的旧正则表达式(?<=\s)\S+(?=%)
,它应该匹配该百分比的数字(例如98.15中的98.15%)。
英文:
I have found the solution, I can just use string replace method to replace all commas with dots, and then use my old regex (?<=\s)\S+(?=\%)
, it should match the number of that percentage (98.15 as in 98.15%)
答案3
得分: 0
\d+(?:[,.]?\d+)?%
英文:
You can also use
\d+(?:[,.]?\d+)?%
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论