模式匹配器不接受parantheses

时间:2016-10-22 16:19:56

标签: java regex matcher

 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)”但它只打印出一个,而不是括号左右括号..有人能告诉我如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

正则表达式中有两个问题:

  1. 您添加了提取空间,以便它可以预期模式中的空间可能会找到您所期望的空间。
  2. 您没有转义括号,这些括号是用于分组的特殊字符。你需要使用双反斜杠来逃避它们。
  3. 您的正则表达式应该是\\(|\\)|a

    <强>输出:

    (
    a
    )
    
相关问题