digeridoo digeridoo - 1 month ago 6
Java Question

Pattern Matcher not accepting parantheses

public class T_token implements Lexer{
static Pattern p = Pattern.compile("\\( | \\) | a");
static Matcher d = p.matcher("( a )");

public static void main(String[] args) {
while (d.find()) {
System.out.println(d.group());
}
}


When I compile and run this, the output is :

run:

a

BUILD SUCCESSFUL (total time: 0 seconds)


So the input I gave the matcher (variable d) was the string "( a )" but it only prints out a, not the parenthesis left and right brackets.. can someone tell me how i can fix this?

Answer

There are 2 issues in your regular expression:

  1. You added extract spaces such that it will expect space in the pattern to find which doesn't seem to be what you expect.
  2. You did not escape the parentheses which are special characters used for grouping. You need to use double backslashes to escape them.

Your regular expression should rather be \\(|\\)|a.

Output:

(
a
)
Comments