2011-04-05 20 views
0

我們如何在java中管理正則表達式?在java中管理正則表達式

是的,我沒有搜索正則表達式的主題,但我認爲它在java中很奇怪。

我想什麼做的是

My team <[email protected]> 

用正則表達式,我想獲得<之間的字符串>作爲[email protected]

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

上面一個也沒有工作。

回答

3

這樣的事情,也許呢?

Pattern p = Pattern.compile("(.+?)<(.*?)>"); 
    Matcher matcher = p.matcher("Foo bar <[email protected]>"); 
    if (matcher.matches()) { 
     System.out.println(matcher.group(2)); 
    } 
+0

例外:否java.util.regex.Matcher.group(來源不明) – smlnl 2011-04-05 21:18:52

+0

奇怪的發現匹配,適用於我的機器上的Java 6。編輯:裏面jUnit4測試,那是:) – 2011-04-05 21:20:50

+0

真的嗎?如果我在循環中執行此模式和匹配器,該怎麼辦?它會改變任何情況嗎? – smlnl 2011-04-05 21:23:46

4

其實你需要調用Matcher對象的find()方法來遍歷字符串。正如Petri Pellinen所說你應該檢查正確的分組。

試試下面的代碼:

String str = "My team <[email protected]> My team <[email protected]> \n " + 
    "My team <[email protected]> My team <[email protected]> " + 
    "My team <[email protected]> My team <[email protected]>"; 

Pattern p = Pattern.compile("\\<(.*?)\\>"); 
Matcher m = p.matcher(str); 

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

,並檢查組牽強。

結果是:

[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 

喝彩!

3

由於看起來您正在處理標準格式的電子郵件地址(RFC 822),您可能需要考慮使用JavaMail API。它旨在處理規範中的所有內容,而使用正則表達式可能會遺漏一些情況。你想要的東西的代碼也很簡單:在線程「主要」 java.lang.IllegalStateException

String input = "My team <[email protected]>"; 
String email = new InternetAddress(input).getAddress();