2017-02-16 63 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 )]