2017-02-16 68 views
0

我有一个要求,其中结果屏幕显示(),[]中的名称。例如:正则表达式或条件

(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

在[Javadoc](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html)中搜索“X或Y”。 –

+2

你想要的确切输出是什么? – IfOnly

+0

试试[']^[(\\ []。*?[)\\]] \\ W *(\\ w +)“'](https://regex101.com/r/PrFogN/1)regex和获取组1('matcher.group(1)')中的值。 –

回答

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+字符除了换行符之外的字符尽可能少至第一个
  • [\\])] -a )]