Regular expression for the percentage of labels
I am trying to create a regex that matches a percentage for labels
For example, if we consider a few percent
1)100%
2)56.78%
3)56 78.90%
4)34.6789%
The corresponding percentages should be
100%
56.78%
34.6789%
I made an expression "\\d.+[\\d]%"
, but it also matches for 56 78.90%
which I don't want.
If anyone knows such an expression, share
source to share
You don't have a double escaping dot, which means its wildcard for any character, including spaces.
Use something like:
┌ integer part  any 1+ number of digits
 ┌ dot and decimal part (grouped)
 ┌ doubleescaped dot
  ┌ decimal part = any 1+ number of digits
   ┌ 0 or 1 greedy quantifier for whole group
   
"\\d+(\\.\\d+)?%"
For example:
String[] inputs = { "100%", "56.78%", "56 78.90%", "34.6789%" };
Matcher m = null;
for (String s: inputs) {
m = p.matcher(s);
if (m.find())
System.out.printf("Found: %s%n", m.group());
}
Output
Found: 100%
Found: 56.78%
Found: 78.90%
Found: 34.6789%
Note
This still matches the 3rd input, but only the last part.
If you want the third input to not match, you can surround your pattern with input boundaries, for example ^
for the start of input and $
for the end of input.
This will become: "^\\d+(\\.\\d+)?%$"
Or you can just call Matcher#matches
instead Matcher#find
.
Next step
You might want to do something about the numeric value you are retrieving.
In this case, you can surround your template with a group ( "(\\d+(\\.\\d+)?)%"
) and call either Double.parseDouble
or new BigDecimal(...)
in your backlink:

Double.parseDouble(m.group(1))

new BigDecimal(m.group(1))
source to share
^ ((100)  (\ d {1,2} (\ d *)).)% $
Check out this regex here: https://regex101.com/r/Ou3mJI/2
You can use this regex. This is true for:
 from 0 to 100 inclusive
 With and without decimal places
The following are valid values:
100% valid
99.802% valid
98.7% valid
57% valid
0% 
This regex is not valid below values:
 Negative numbers
 Number> 100
 Number with spaces
Invalid values:
1%
99.989%
101%
56 78.90%
Hope this helps!
source to share