digeridoo digeridoo - 3 years ago 79
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()) {

When I compile and run this, the output is :



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 Source

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.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download