2009-03-26 7 views
0

の間に含まれる文字列を検索するには、[[STを:それは]で終わる]正規表現は、このテキストでセパレータ

私のプログラムが出力します:

 
aaa bbb ccc ddd eee fff (first match) 
ggg hhh iii jjj kkk \n lll mmm nnn(second match) 

しかし、私は最初の[[st:そして最後の]]を返すことしかできないので、2つではなく1つのマッチがあります。何か案は?

はここに私のコードです:

package com.s2i.egc.test; 

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

public class TestRegex { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 

     String bodyText = "text text text [[st: aaa bbb ccc ddd eee fff]] text text text text [[st: ggg hhh iii jjj kkk\n lll mmm nnn]] text text text"; 

     String currentPattern = "\\[\\[st:.*\\]\\]"; 

     Pattern myPattern = Pattern.compile(currentPattern, Pattern.DOTALL); 

     Matcher myMatcher = myPattern.matcher(bodyText); 

     int i = 1; 

     while (myMatcher.find()) { 
      String match = bodyText.substring(myMatcher.start() + 5, myMatcher.end() - 3); 
      System.out.println(match + " (match #" + i + ")"); 
      i++; 
     }       


    } 

} 

答えて

3

数量詞の*(0以上)は貪欲ですデフォルトでは、2番目の[]に一致します)。

は消極的パターンマッチに変更してみてください:

String currentPattern = "\\[\\[st:.*?\\]\\]"; 
+0

ありがとう!出来た! :) – mrmuggles

2

あなたが代わりに

.* 

使用アスタリスクのために怠惰なモードを使用する必要があります。

"\\[\\[st:.*?\\]\\]" 
1

ちょうど完全ために、非貪欲星なしで、あなたはどんな以外]の文字が続くオープニング[[STを:,一致することができ、可能であれば非文字]の後に[]の文字列を含む可能性があります]最後に]]:

\[\[st:([^\]]*(?:\][^\]]+)*)\]\] 
関連する問題