正则表达式或条件

时间:2017-02-16 11:41:59

标签: java regex

我要求结果屏幕在(),[]中显示名称。例如:

(son of X) (Smith),(son of X) Smith
[Son of X] Smith
[Son of X] [Smith]

我想要检索其中的第一个名字。我为第一个字符串尝试了以下正则表达式,但它没有帮助:

        String name="(son of x) (Smith)";
        Matcher matcher = Pattern.compile("\\(.*\\)\\b").matcher(name);
        while (matcher.find() ) {
              System.out.println(matcher.group() );
         }

有人可以帮助形成正则表达式吗?还请告诉我们如何给出条件或条件?

1 个答案:

答案 0 :(得分:0)

您需要使用^将搜索锚定在字符串的开头,然后匹配([,然后捕获 0+其他字符,直到第一个)]

请参阅Java demo

//String s = "(son of X) (Smith),(son of X) Smith"; // son of X
String s = "[Son of X] Smith"; // Son of X
Pattern pattern = Pattern.compile("^[(\\[](.*?)[\\])]");
Matcher matcher = pattern.matcher(s);
if (matcher.find()){
    System.out.println(matcher.group(1)); 
}

<强>详情:

  • ^ - 字符串开头
  • [(\\[] - [(
  • (.*?) - 第1组:除了换行符之外的任何0 +字符尽可能少到第一个字符
  • [\\])] - )]
相关问题