匹配百分比中仅包含逗号或点分隔的数字的正则表达式

huangapple go评论59阅读模式
英文:

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 (?&lt;=\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 (?&lt;=\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+)?%

huangapple
  • 本文由 发表于 2023年6月9日 12:49:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76437284.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定