I have a problem with regards to writing the correct regex for the examination rating field of my grails application. Users should have the option to either enter an alphabet character OR a number. Quantitative rating should range from 0-100, accepts decimal numbers with or without percentage sign (%) but exclude negative numbers. The regex should permit special characters percentage(%) and period (.) ONLY. Below is a set of possible input:
1) 100% (should pass the validation)
2) 100.0 (should pass the validation)
3) PASSED (should pass the validation)
4) FAILED (should pass the validation)
5) 100.1 (should not pass the validation)
6) -90 (should not pass the validation)
Your answer will be highly appreciated.
Thanks!
I assume the language is Java. I also assume that you want to validate user input, which expects to contain only the percentage.
(In Groovy, you don’t have to escape the backslash)
The regex above will only validate numbers between 0.0 to 100.0. It allows arbitrary long number of digits after decimal points, and also allows cases such as
.8or45.to pass, since they can be processed. The regex also allows any amount of spaces before and after the input (but not inside).EDIT
To match plain text (ASCII):
This will match text that uses English alphabet character (case-insensitive), and full-period. E.g.
sdhSDFHS.sfSDJF.sdfSDJFIwill matches the above regex. Note that the current regex does not allow spaces within the text, but if you want to add more characters, add inside the square bracket (character class):[a-zA-Z.]. Check the documentation for more details.Testing code (for Java)
Output
EDIT2
Change in requirement as mentioned in the discussion: only match from 1.0 to 100.0 inclusive for the percentage:
This condition is even more stricter than before, since
01.1will not match. If you want to match this case: