How to use pattern matching correctly in java


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


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");


I want this to print "10" only if there is a match, but this throws a PatternSyntaxException. Can someone give me an epiphany please?



source to share

2 answers

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:



Note that with all those unnecessary backslashes, you forgot the separator.



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 band if(matchOp1.find())


Instead, it should look like this:



and when used in code:

Pattern pattern = Pattern.compile("(\\d+)(\\s)([\\+\\-\\*\\%\\^])(\\s)(\\d+)");
Matcher matchOp1 = pattern.matcher("1 + 1");





All Articles