2012-11-18 61 views
2

是否有任何方法使用正則表達式拆分Java字符串並返回一組反向引用?Java - 數組中的正則表達式反向引用

舉一個簡單的例子,假設我想從一個簡單的電子郵件地址(僅限字母)提取用戶名&。

String pattern = "([a-z]+)@([a-z]+)\\.([a-z]{3})"; 
String email = "[email protected]"; 

String[] backrefs = backrefs(email,pattern); 

System.out.println(backrefs[0]); 
System.out.println(backrefs[1]); 
System.out.println(backrefs[2]); 

這應該輸出

user 
email 
com 

回答

5

是,利用java.util.regex pacakge的PatternMatcher類。

String pattern = "([a-z]+)@([a-z]+)\\.([a-z]{3})"; 
String email = "[email protected]"; 
Matcher matcher = Pattern.compile(pattern).matcher(email); 
// Check if there is a match, and then print the groups. 
if (matcher.matches()) 
{ 
    // group(0) contains the entire string that matched the pattern. 
    for (int i = 1; i <= matcher.groupCount(); i++) 
    { 
     System.out.println(matcher.group(i)); 
    } 
} 
+0

正是我在找什麼,謝謝! –