2011-09-14 11 views
0

我的文字像這樣的字符串:Java正則表達式查找字符串把它添加到陣列,然後替換原來的

This is a[WAIT] test. 

我想要做的是搜索字符串與啓動子[和結尾] 每一個我覺得我想它在原始字符串以^

這添加到一個ArrayList和替換子是我的正則表達式:

String regex_script = "/^\\[\\]$/"; //Match a string which starts with the character [ ending in the character ] 

這裏是我的到目前爲止:

StringBuffer sb = new StringBuffer(); 

Pattern p = Pattern.compile(regex_script); // Create a pattern to match 
Matcher m = p.matcher(line); // Create a matcher with an input string 
boolean result = m.find(); 
     while(result) { 
       m.appendReplacement(sb, "^"); 
       result = m.find(); 
     } 
     m.appendTail(sb); // Add the last segment of input to the new String 

我該怎麼做到這一點?謝謝

回答

2

,你可以這樣做:

String regex_script = "\\[([^\\]]*)\\]"; 

    String line = "This is a[WAIT] testThis is a[WAIT] test"; 
    StringBuffer sb = new StringBuffer(); 
    List<String> list = new ArrayList<String>(); //use to record 

    Pattern p = Pattern.compile(regex_script); // Create a pattern to match 
    Matcher m = p.matcher(line); // Create a matcher with an input string 

    while (m.find()) { 
     list.add(m.group(1)); 
     m.appendReplacement(sb, "[^]"); 
    } 
    m.appendTail(sb); // Add the last segment of input to the new String 

    System.out.println(sb.toString()); 
+0

工作得很好!感謝 - 這個問題並不熟悉某些轉義序列如何影響模式。 – GideonKain

+0

@ouotuo嗨,你可以看看這個問題嗎? http://stackoverflow.com/questions/34938232/android-regex-passing-of-text-output-from-method-to-method –

-1

如果您要搜索子字符串,請不要使用^和$。這些是開始和一個字符串(而不是字)結束嘗試:

String regex_script = "/\[.*\]/"; 
+1

沒有,在Java字符串文字裏面,反斜槓需要轉義再一次,Java的正則表達式不能用像'/'這樣的字符來分隔。 –