模式匹配器不接受括号

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

当我编译 运行 时,输出是:

run:

 a

BUILD SUCCESSFUL (total time: 0 seconds)

所以我给匹配器(变量 d)的输入是字符串“( a )”,但它只打印出 a,而不是左右括号。有人能告诉我如何解决这个问题吗?

你的正则表达式有两个问题:

  1. 您添加了提取物 spaces,这样它会期望 space 在模式中找到与您期望的不符的内容。
  2. 您没有转义用于分组的特殊字符括号。您需要使用双反斜杠来转义它们。

您的正则表达式应该是 \(|\)|a.

输出:

(
a
)