我有这种情况:
我的字符串:
Try a lot of match groups
[COD_BODY="AZI_DIP-ANAG_AZI", LABEL="Apri link1"] come on Taranto
[ COD_BODY="AZI_DIP-ANAG_AZI", LABEL="Apri link2"]
[ COD_BODY ="AZI_DIP-ANAG_AZI", LABEL="Apri link3"]
[ COD_BODY = "AZI_DIP-ANAG_AZI", LABEL="Apri link4"]
[ COD_BODY = "AZI_DIP-ANAG_AZI", LABEL ="Apri link5"]
[ COD_BODY = "AZI_DIP-ANAG_AZI", LABEL = "Apri link6"]
[ COD_BODY = "AZI_DIP-ANAG_AZI" , LABEL = "Apri link5" ]
我已经写过这个面具(用Java编写):
"(\\[(\\s*)\\bCOD_BODY(\\s*)=(\\s*)\"(.*)?\"(\\s*),(\\s*)LABEL(\\s*)=(\\s*)\"(.*)?\"(\\s*)\\]*)"
我在Pattern.compile
中使用了这种模式现在......如果我试试这些网站:
和http://ocpsoft.org/tutorials/regular-expressions/java-visual-regex-tester
使用这种模式:
(\[(\s*)\bCOD_BODY(\s*)=(\s*)"(.*)?"(\s*),(\s*)LABEL(\s*)=(\s*)"(.*)?"(\s*)\]*)
我已删除了在Java中使用的双\以逃避特殊字符
结果是:找到了7个匹配项!
但是在Java while(matcher.find())
中只循环一次而不是七次!
请问,我的错在哪儿?
如果您有进一步的信息,请评论此问题。
答案 0 :(得分:2)
我无法重现您的问题:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex {
public Regex() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
String input = "Try a lot of match groups\r\n" +
"\r\n" +
"[COD_BODY=\"AZI_DIP-ANAG_AZI\", LABEL=\"Apri link1\"] come on Taranto\r\n" +
"\r\n" +
"[ COD_BODY=\"AZI_DIP-ANAG_AZI\", LABEL=\"Apri link2\"]\r\n" +
"\r\n" +
"[ COD_BODY =\"AZI_DIP-ANAG_AZI\", LABEL=\"Apri link3\"]\r\n" +
"\r\n" +
"[ COD_BODY = \"AZI_DIP-ANAG_AZI\", LABEL=\"Apri link4\"]\r\n" +
"\r\n" +
"[ COD_BODY = \"AZI_DIP-ANAG_AZI\", LABEL =\"Apri link5\"]\r\n" +
"\r\n" +
"[ COD_BODY = \"AZI_DIP-ANAG_AZI\", LABEL = \"Apri link6\"]\r\n" +
"\r\n" +
"[ COD_BODY = \"AZI_DIP-ANAG_AZI\" , LABEL = \"Apri link5\" ]";
Pattern pattern = Pattern.compile("(\\[(\\s*)\\bCOD_BODY(\\s*)=(\\s*)\"(.*)?\"(\\s*),(\\s*)LABEL(\\s*)=(\\s*)\"(.*)?\"(\\s*)\\]*)");
Matcher matcher = pattern.matcher(input);
while(matcher.find()) {
System.out.println(matcher.group());
}
}
}
结果:
[COD_BODY="AZI_DIP-ANAG_AZI", LABEL="Apri link1"]
[ COD_BODY="AZI_DIP-ANAG_AZI", LABEL="Apri link2"]
[ COD_BODY ="AZI_DIP-ANAG_AZI", LABEL="Apri link3"]
[ COD_BODY = "AZI_DIP-ANAG_AZI", LABEL="Apri link4"]
[ COD_BODY = "AZI_DIP-ANAG_AZI", LABEL ="Apri link5"]
[ COD_BODY = "AZI_DIP-ANAG_AZI", LABEL = "Apri link6"]
[ COD_BODY = "AZI_DIP-ANAG_AZI" , LABEL = "Apri link5" ]
答案 1 :(得分:0)
如果您的模式与整个字符串匹配,则不应在循环中调用find()
。相反,你必须从匹配器中提取组:
Matcher m = pattern.matcher(str);}
if (!m.find()) { // call find only once!
return;
}
int n = m.groupCount();
for(int i = 1; i <= n; i++) { // starting from 1
String capture = m.group(i); // this is the captured group.
// deal with capture
}