【问题标题】:How to get the values from outside the braces using regex如何使用正则表达式从大括号外获取值
【发布时间】:2014-07-25 06:38:27
【问题描述】:

请参阅下面的要求。

String s1 = "||||(;)||(;;)||(;)";

上述字符串的输出应该是:||||||

String s2 = ";;(||)";

上述字符串的输出应该是:;;

String s3 = ";;";

上述字符串的输出应该是:;;

我正在尝试下面的示例,但 s1 的输出是 ;

Pattern p = Pattern.compile("\\(^(.*?)\\)");
Matcher m = p.matcher(filter);

while (m.find()) {
    System.out.println(m.group(1));
}

【问题讨论】:

    标签: java javascript regex


    【解决方案1】:

    由于您只删除了可以使用的大括号内的所有内容:

    str.replaceAll("\([^\)]*\)", "");
    

    【讨论】:

    • 你打败了我,+1。 :)
    • 没想到replaceAll :P.. +1
    【解决方案2】:

    试试这个正则表达式..

    public static void main(String[] args) {
        String s1 = "||||(;)||(;;)||(;)";
        Pattern p = Pattern.compile("(.*?)(?:\\(.*?\\))");
        Matcher m = p.matcher(s1);
        while (m.find()) {
            System.out.println(m.group(1));
        }
    
    }
    

    O/P:

    case -1 : s1 = "||||(;)||(;;)||(;)";
    ||||
    ||
    ||
    
    case -2 :   s1 = ";;(||)";
    
        ;;
    

    【讨论】:

      猜你喜欢
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 2023-01-14
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多