我正在使用Pattern and Matcher创建一个正则表达式,它将从下面的li标记中提取6个值:
<ul class="Bold"> <li class="ball-orange">2</li> <li class="ball-orange">10</li> <li class="ball-orange">11</li> <li class="ball-orange">15</li> <li class="ball-orange">22</li> <li class="ball-orange">39</li> </ul>
即正则表达式的结果必须是具有2、10、11、15、22、39的组。
我有以下代码:
Pattern numbersPattern = Pattern.compile(".*(<li class=\"ball-orange\">([0-9]{1,2})</li>).*");
Matcher matchNumbers = numbersPattern.matcher(mainBlock);//mainBlock is the string I quoted above which contains all the li's
System.out.println("Numbers Match? " + matchNumbers.matches());//this returns true
System.out.println(matchNumbers.group(2));//returns 39, i.e. second group but for the last li
//this loop never gets entered!!!
while (matchNumbers.find()) {
System.out.println("group 1: " + matcher.group(1));
System.out.println("group 2: " + matcher.group(2));
//System.out.println("group 3: " + matcher.group(3));
}
因此,它与您从注释中看到的最后一个li匹配,但不会进入while(matchNumbers.find())循环。即我想(<li class=\"ball-orange\">([0-9]{1,2})</li>)
被发现6次,并在循环中输出,但事实并非如此。
我正在关注以下内容-http: //tutorials.jenkov.com/java-regex/matcher.html#groups-inside-groups。
为什么不输入循环,我如何才能匹配李的组?
当前,您正急切地匹配整个字符串(任何+ li +任何),这就是原因matches() == true
。如果需要全部,只需移除.*
零件,因为.find()
会多次找到您的图案,首先在〜25位置,然后在〜60位置,依此类推:
String mainBlock = "<ul class=\"Bold\"> <li class=\"ball-orange\">2</li> <li class=\"ball-orange\">10</li> <li class=\"ball-orange\">11</li> <li class=\"ball-orange\">15</li> <li class=\"ball-orange\">22</li> <li class=\"ball-orange\">39</li> </ul>";
Pattern listPattern = Pattern.compile("<li class=\"ball-orange\">([0-9]{1,2})</li>");
Matcher matcher = listPattern.matcher(mainBlock);
while (matcher.find()) {
System.out.println("whole thing: " + matcher.group()); // or group(0)
System.out.println("number: " + matcher.group(1));
}
整个物品:<li class =“ ball-orange”> 2 </ li>
数量:2
整个物品:<li class =“ ball-orange”> 10 </ li>
数量:10
整个物品:<li class =“ ball-orange“> 11 </ li>
编号:11
全部:<li class =” ball-orange“> 15 </ li>
编号:15
整体:<li class =” ball-orange“> 22 </ li>
编号:22
整件事:<li class =“ ball-orange”> 39 </ li>
编号:39
注意:您无需在整个正则表达式周围放置一个组,从定义上讲,捕获组0就是整个匹配项,这就是为什么编号从1开始。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句