2012-02-02 76 views
0

我想獲得標籤內的文字,例如<text>。我做:Java:這個正則表達式有什麼問題?

Pattern pattern = Pattern.compile("(?<=\\<).*(?=\\>)"); 

我認爲這表示:任意字符0次或更多次,以前是<(正回顧後),並隨後>(正前瞻)。

Matcher m = pattern.matcher(data); 
if (!m.matches()) continue; //Called in a for loop 

但是沒有匹配例如輸入​​。

我在這裏做錯了什麼?

回答

5

請勿使用m.matches(),而應使用m.find()

JavaDocmatches()

嘗試的整個區域與模式相匹配。

+0

謝謝!但我現在還不確定'匹配'是什麼意思。我的意思是整個區域在這種情況下是什麼 – Cratylus 2012-02-02 08:06:54

+0

@ user384706整個區域是您想要匹配的整個字符串,即「data」的整個內容在你的情況。 – Thomas 2012-02-02 08:58:35

1

你可以試試這個匹配:

public static void main(String[] args) { 
    String input = "<text> Some Value </text> <a> <testTag>"; 
    Pattern p = Pattern.compile("<(\\w.*?)>"); 
    Matcher m = p.matcher(input); 

    while(m.find()){ 
     System.out.println(m.group(1)); 
    } 
} 
5

當您使用matches(),整個輸入字符串必須表達匹配。如果您想查找子字符串,則可以使用find()代替。

0

我不太明白你的正則表達式,但這個工作對我來說:

String text = "<text>"; 
Pattern p = Pattern.compile(".*<(.*)>.*"); 
Matcher m = p.matcher(text); 
System.out.println(m.matches()); 
System.out.println(m.group(1)); 

這顯示:

true 
text 

是你需要什麼?

相關問題