2011-06-14 142 views
2

我試圖讓每一個簡單的正則表達式的重複比賽中的Java:Java的重複模式匹配

(\\[[^\\[]*\\])* 

其包含在[],只要它不包含[任意字符串匹配字符。例如,它會匹配

[a][nice][repetitive][pattern] 

之前沒有多少存在這樣的羣體知識,我無法找到通過模式匹配器訪問各個匹配組的方式,即不能獲得

[a], [nice], [repetitive], [pattern] 

(或者,甚至更好,而括號中的文字),在4名不同的字符串。

使用pattern.matcher()我總是在最後一組。

當然必須有在Java中這樣做的一個簡單的方法,我很想念?

感謝您的任何幫助。

回答

5
String string = "[a][nice][repetitive][pattern]"; 
    String regexp = "\\[([^\\[]*)\\]"; 
    Pattern pattern = Pattern.compile(regexp); 
    Matcher matcher = pattern.matcher(string); 
    while (matcher.find()) { 
     System.out.println(matcher.group(1)); 
    } 
+0

請您解釋一下您的正則表達式?謝謝。 – 2012-09-17 05:00:01

1

這是我嘗試:)

import java.util.ArrayList; 
import java.util.List; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class Foo { 
    public static void main(String[] args) { 
     final String text = "[a][nice][repetitive][pattern]"; 
     System.out.println(getStrings(text)); // Prints [a, nice, repetitive, pattern] 
    } 

    private static final Pattern pattern = Pattern.compile("\\[([^\\]]+)]"); 

    public static List<String> getStrings(final String text) { 
     final List<String> strings = new ArrayList<String>(); 
     final Matcher matcher = pattern.matcher(text); 
     while(matcher.find()) { 
      strings.add(matcher.group(1)); 
     } 
     return strings; 
    } 

} 
+0

請你解釋一下你的正則表達式? – 2012-09-30 14:33:50

2

我會用分裂

String string = "[a][nice][repetitive][pattern]"; 
String[] words = string.substring(1, string.length()-1).split("\\]\\["); 
System.out.println(Arrays.toString(words)); 

打印

[a, nice, repetitive, pattern]