我有源字符串"This is my test string"
並想提取使用特定模式的IT價值:"{0} is my {1} string"
如何匹配匹配組的字符串以提取值?
我想提取如This
和test
這裏。我如何使用正則表達式匹配組來編寫它?
以下是我想出的某種僞代碼。但我不知道究竟如何實現這些匹配組:
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)
?那可能嗎?
你應該在1開始而不是0。'.group(0)'總是返回匹配器匹配的全文。另外,由於正則表達式匹配輸入,它應該在輸出中打印'test'。 – fge
好的,我明白了。是的,它也打印'測試',相應地調整我的問題。 – membersound