0

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.

shellawa
  • 11
  • 3

3 Answers3

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 .

M H
  • 325
  • 3
  • 8
  • But in that case, how can I know if it’s 98% or 9.8%? I don’t think everyone would write 98.00% – shellawa Jun 09 '23 at 06:05
  • Oh, I can just replace comma with dot and use my old way, thanks for pointing out – shellawa Jun 09 '23 at 06:06
  • Check out string padding: https://www.geeksforgeeks.org/add-padding-to-a-string-in-python/ You should be aware of float conversion `float("23.23")` (and locale issues: https://stackoverflow.com/questions/6633523/how-can-i-convert-a-string-with-dot-and-comma-into-a-float-in-python) Also consider someone doing something greater than 100%, could they use both comma and `.`? e.g. `5,000.95%`? – M H Jun 09 '23 at 07:18
  • locale is such an issue, it's good that a "play" never exceeds 100% tho. thanks for the information – shellawa Jun 09 '23 at 14:24
1

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%)

shellawa
  • 11
  • 3
0

You can also use

\d+(?:[,.]?\d+)?%
Reilas
  • 3,297
  • 2
  • 4
  • 17