java正则表达式提取xxxx(yyyy)中的内容

在古诗中,我们提取到了题目与作者在一起的数据,如

行宫(元稹)

里面的括号是英文括号,现在要分别提取出标题与作者。有两种方案:

(1)通过split得到

      String [] strArray = Pattern.compile("\(|\)").split("行宫(元稹)");
        for (String str : strArray){
            System.out.println(str);
        }

 

 输出为

行宫
元稹

(2)通过普通捕获组得到

Pattern p = Pattern.compile("(.*)(\()(.*)(\))");
        Matcher m = p.matcher("行宫(元稹)");
        if (m.find()){
            System.out.println(m.group(1));
            System.out.println(m.group(3));
        }

 输出同上。

 

 

 

 

原文地址:https://www.cnblogs.com/chuiyuan/p/5187514.html