I'm learning regular expression as part of my Java course. Now I know sometimes the best use of regex is to not use regex at all. But since I have to use it for this course and learn it, I figure I might as well learn it properly.
I am matching (##/##)
or (##)
where #
is a number 0-9
. All white space is ignored (except for in between the digits ##
). In context, I'm matching a fraction (10/20)
or a percentage (50)
.
For example ( ## / ## )
and ( ## )
are valid. (# #/# #)
and (# #)
are not.
Code / Explanation:
(?:[(])(?:[ ]*)?([\d][\d])(?:[ ]*)?(?:[\/])?(?:[ ]*)?([\d][\d])?(?:[ ]*)?(?:[)])
(?:[(]) Beginning parathensis (
(?:[ ]*)? All white space
([\d][\d]) Two digits for the first number ##
(?:[ ]*)? All white space
(?:[\/])? Forward slash /
(?:[ ]*)? All white space
([\d][\d])? Two digits for the second number ##
(?:[ ]*)? All white space
(?:[)]) Closing parathensis )
Example usage in Java:
String regex = "(?:[(])(?:[ ]*)?([\\d][\\d])(?:[ ]*)?(?:[\\/])?(?:[ ]*)?([\\d][\\d])?(?:[ ]*)?(?:[)])";
String test = "(20/50)";
if (test.matches(regex)) { // true
System.out.println("Valid.");
else {
System.out.println("Invalid.");
}
Everything is setup using non-capture groups, except for the two digits. This is so I can reference the capture groups in my code (and simply check if group 2 is null before trying to use it, indicating (##)
not (##/##)
).
This is basically my first time writing regex from complete scratch. Some questions are:
- Should I be wrapping everything in
[ ]
even when they can be left out? i.e.(?: *)
instead of(?:[ ]*)
. - Is my use of non-capture groups the right way to do things (feels verbose to me)?
Generally, what can I improve on?