带有或条件的正则表达式

内哈

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

(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() );
         }

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

威克多·斯特里比尤(WiktorStribiżew)

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

参见Java演示

//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+字符都应尽可能少,直到第一个
  • [\\])]-一个)]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章