How to use pattern matching correctly in java
Update:
I found a solution thanks to @dasblinkenlight and all the other good samaritans. Working code here for any of you with a similar question:
Pattern pattern = Pattern.compile("(\\d+)(\\s)([-+*%/^])(\\s)(\\d+)");
Matcher matchOp1 = pattern.matcher(text);
matchOp1.find();
System.out.println(matchOp1.group(1));
This will only display the first group.
Original question:
First of all, I cannot use any if statements, so I have to catch and handle only exceptions.
Suppose I have a string containing "10 + 20".
I have the following regular expression: "(\ d \ +) (\ s) ([\ + \ - \ * \% \ ^]) (\ s) ([\ d \ +)". This regex is meant to match (integer of any length) (space) (operator) (space) (integer of any length)
Pattern pattern = Pattern.compile("(\\d\\+)(\\s)([\\+\\-\\*\\%\\^])(\\s)([\\d\\+)");
Matcher matchOp1 = pattern.matcher("1 + 1");
System.out.println(matchOp1.group(1));
I want this to print "10" only if there is a match, but this throws a PatternSyntaxException. Can someone give me an epiphany please?
Thank!
source to share
You have an extra [
in your template and you avoid the pros that you shouldn't:
Pattern pattern = Pattern.compile("(\\d\\+)(\\s)([\\+\\-\\*\\%\\^])(\\s)([\\d\\+)");
// ^^ ^ ^^
Removing these issues will fix the problem.
Note that escaping metacharacters within a character class [...]
is optional: just be careful to move -
to one end and place ^
to any position other than the first:
"(\\d+)(\\s)([-+*%/^])(\\s)(\\d+)"
Note that with all those unnecessary backslashes, you forgot the separator.
source to share
You have some problems with your regex
Pattern pattern = Pattern.compile("(\\d\\+)(\\s)([\\+\\-\\*\\%\\^])(\\s)([\\d\\+)");
^ ^ ^
- You haven't closed the square brackets
- You shouldn't avoid
+
it as there is more than 1 digit in there and not literally+
. - He will be throwing
IllegalStateException
, so you have to place before recording the bandif(matchOp1.find())
.
Instead, it should look like this:
(\d+)(\s)([\+\-\*\%\^])(\s)(\d+)
and when used in code:
Pattern pattern = Pattern.compile("(\\d+)(\\s)([\\+\\-\\*\\%\\^])(\\s)(\\d+)");
Matcher matchOp1 = pattern.matcher("1 + 1");
if(matchOp1.find())
System.out.println(matchOp1.group(1));
source to share