2013-11-04 30 views
0

我有一個StringMatcher.group和正則表達式不充分提取正則表達式

String s = "adfgadfbfgadg sa 2419sfgh"; 

我想提取子

String substring = "sa 2419sfgh"; 

與Pattern和Matcher使用下面的正則表達式和代碼。

formNumberRegex = "[al|sf|sa|sc|nrc|nrc form|doe|doe f|lsi|doe form psd f|doe al f]?[\\s\\-\\.]*[\\d]{3,6}[\\s\\-\\.]*[\\w]{1,4}"; 
formNumberRegexPattern = Pattern.compile(formNumberRegex); 
formNumberMatcher = formNumberRegexPattern.matcher(s); 

if (formNumberMatcher.find()) { 
    String substring = formNumberMatcher.group(); 
} 

不過,我只得到

substring = "a 2419sfgh"; 

什麼是錯我的正則表達式和/或匹配器?

回答

3

,我立即注意到:

[al|sf|sa|sc|nrc|nrc form|doe|doe f|lsi|doe form psd f|doe al f]? 

應該是:

(?:al|sf|sa|sc|nrc|nrc form|doe|doe f|lsi|doe form psd f|doe al f)? 

「非捕獲組」(?),讓您避免捕獲第一部分作爲初始組。這樣,整個表達就是「匹配組0」,就是這樣。

這裏測試:http://regex101.com/r/lS9dT2

1

您正在使用character class[...]

[al|sf|sa|sc|nrc|nrc form|doe|doe f|lsi|doe form psd f|doe al f] 

,而不是group

(al|sf|sa|sc|nrc|nrc form|doe|doe f|lsi|doe form psd f|doe al f) 

你用什麼可以寫爲

(\\||a|l|s|f|s|a|s|c|n|r|c|n|r|c| |f|o|r|m|d|o|e|d|o|e| |f|l|s|i|d|o|e| |f|o|r|m| |p|s|d| |f|||d|o|e| |a|l| |f) 

如此以來字符類將匹配所有使用只有一個字符內[...]會等接受|als ...和,而修改後的版本將只接受或喜歡alsf分離的情況下一個等等。

所以,你的正則表達式改爲

String formNumberRegex = "(al|sf|sa|sc|nrc|nrc form|doe|doe f|lsi|doe form psd f|doe al f)?[\\s\\-\\.]*[\\d]{3,6}[\\s\\-\\.]*[\\w]{1,4}";