【问题标题】:Extracting string from within round brackets in Java with regex使用正则表达式从Java中的圆括号中提取字符串
【发布时间】:2015-07-17 12:00:28
【问题描述】:

我正在尝试从圆括号中提取字符串。
假设我有John Doe (123456789),我只想输出字符串123456789

我找到了this link 和这个正则表达式:

/\(([^)]+)\)/g

但是,我无法弄清楚如何获得想要的结果。

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 你的输入输出是什么?引用的帖子显示了如何获取第 1 组的值。
  • 输入是字符串,输出也是字符串。

标签: java regex brackets


【解决方案1】:
String str="John Doe (123456789)";
System.out.println(str.substring(str.indexOf("(")+1,str.indexOf(")")));

这里我正在执行字符串操作。我对正则表达式不太熟悉。

【讨论】:

    【解决方案2】:

    你需要在你的正则表达式中转义括号:

        String in = "John Doe (123456789)";
    
        Pattern p = Pattern.compile("\\((\\d*)\\)");
        Matcher m = p.matcher(in);
    
        while (m.find()) {
            System.out.println(m.group(1));
        }
    

    【讨论】:

      【解决方案3】:

      这对我有用:

      @Test
      public void myTest() {
          String test = "test (mytest)";
          Pattern p = Pattern.compile("\\((.*?)\\)");
          Matcher m = p.matcher(test);
      
          while(m.find()) {
              assertEquals("mytest", m.group(1));
          }
      }
      

      【讨论】:

        【解决方案4】:

        在Java中,你需要使用

        String pattern = "\\(([^()]+)\\)";
        

        那么,你需要的值在.group(1)中。

        String str = "John Doe (123456789)";
        String rx = "\\(([^()]+)\\)";
        Pattern ptrn = Pattern.compile(rx);
        Matcher m = ptrn.matcher(str);
        while (m.find()) {
          System.out.println(m.group(1));
        }
        

        IDEONE demo

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-09
          • 2018-01-12
          • 2015-12-27
          • 2021-11-20
          • 1970-01-01
          相关资源
          最近更新 更多