使用组的Java-Reg表达式
从字符串中,我需要拉出与给定模式匹配的组 示例字符串:使用组的Java-Reg表达式,java,regex,Java,Regex,从字符串中,我需要拉出与给定模式匹配的组 示例字符串:FIRSTSECONDThird 每组应以开始,以结束。这是我的一段代码 String patternStr = "(<XmlLrvs>.+?</XmlLrvs>)+"; // Compile and use regular expression Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(text)
FIRSTSECONDThird
每组应以
开始,以
结束。这是我的一段代码
String patternStr = "(<XmlLrvs>.+?</XmlLrvs>)+";
// Compile and use regular expression
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(text);
matcher.matches();
// Get all groups for this match
for (int i = 1; i<=matcher.groupCount(); i++) {
System.out.println(matcher.group(i));
}
String patternStr=“(.+?)+”;
//编译并使用正则表达式
Pattern=Pattern.compile(patternStr);
Matcher Matcher=pattern.Matcher(文本);
matcher.matches();
//获取此比赛的所有组
对于(int i=1;i当您应该迭代匹配项时,您正在迭代组。matches()
方法检查整个输入是否匹配。您需要的是find()
方法
改变
matcher.matches();
for (int i = 1; i<=matcher.groupCount(); i++) {
System.out.println(matcher.group(i));
}
试试看
字符串模式str=“(.*?”;
String text=“FIRSTSECONDThird”
Pattern=Pattern.compile(patternStr);
Matcher Matcher=pattern.Matcher(文本);
而(matcher.find()){
System.out.println(matcher.group(1));
}
输出为第一、第二、第三
请注意,需要删除正则表达式中的+,否则所有内容都将立即匹配,而不是在三次迭代中匹配。我不同意这一点,.+?是一个非贪婪的量词。但我还没有对它进行测试。删除表达式尾部的+并使用while-control语句就可以了。Thanks@molf:好的你,我没看见!
while (matcher.find()) {
System.out.println(matcher.group(1));
}