2014-03-12 109 views
0

我有源字符串"This is my test string"並想提取使用特定模式的IT價值:"{0} is my {1} string"如何匹配匹配組的字符串以提取值?

我想提取如Thistest這裏。我如何使用正則表達式匹配組來編寫它?

以下是我想出的某種僞代碼。但我不知道究竟如何實現這些匹配組:

Matcher match = Pattern.compile("(.*) is my (.*) string").matcher("This is my test string"); 
if (match.matches()) { 
    for (int i = 0; i <= match.groupCount(); i++) { 
     Sysout(match.group(i)); 
    } 
} 

打印:

This is my test string 
This 
test 

但我想獲得:

This 
test 

我怎樣才能防止把整個字符串作爲匹配組?或者我可以直接將匹配綁定到特定的匹配組? Like​​其中test會去match.group(0)?那可能嗎?

+3

你應該在1開始而不是0。'.group(0)'總是返回匹配器匹配的全文。另外,由於正則表達式匹配輸入,它應該在輸出中打印'test'。 – fge

+0

好的,我明白了。是的,它也打印'測試',相應地調整我的問題。 – membersound

回答

2

除了在註釋中提到的組索引問題,還有另一個問題:

[...]ç我是否也應該直接將比賽綁定到特定的匹配組?像{1}是我的{0}字符串,其中測試將進入match.group(0)?那可能嗎?

不使用Java 6.使用Java 7+,可以使用指定的捕獲組:

Pattern.compile("(?<first>.*) is my (?<second>.*) string") 

然後,您可以在您的Matcher實例使用.group("first").group("second")

請注意,.group()相當於.group(0)

1

組0總是匹配的字符串。您定義的正則表達式中的匹配組始終開始從1

具有在javadoc for Matcher.group(int)一個贓物:

零組表示整個模式,所以表達式m.group(0)是相當於 m.group()