[英]Java regex pattern matching not working for second occurrence
我正在使用 java.util.Regex 来匹配字符串中的正则表达式。 该字符串基本上是一个html字符串。
在那个字符串中,我有两行;
<style>templates/style/color.css</style>
<style>templates/style/style.css</style>
我的要求是获取样式标签( <style>
)内的内容。 现在我正在使用这样的模式;
String stylePattern = "<style>(.+?)</style>";
当我试图得到结果时;
Pattern styleRegex = Pattern.compile(stylePattern);
Matcher matcher = styleRegex.matcher(html);
System.out.println("Matcher count : "+matcher.groupCount()+ " and "+matcher.find()); //output 1
if(matcher.find()) {
System.out.println("Inside find");
for (int i = 0; i < matcher.groupCount(); i++) {
String matchSegment = matcher.group(i);
System.out.println(matchSegment); //output 2
}
}
我从输出 1 得到的结果为:
Matcher count : 1 and true
并从输出 2 作为;
<style>templates/style/style.css</style>
现在,经过大量尝试后,我迷失了如何获得两条线。 我在 stackoverflow 本身中尝试了许多其他建议,但都没有奏效。
我想我在做一些概念上的错误。
任何帮助都会对我有好处。 提前致谢。
编辑
我已将代码更改为;
Matcher matcher = styleRegex.matcher(html);
//System.out.println("find : "+matcher.find() + "Groupcount = " +matcher.groupCount());
//matcher.reset();
int i = 0;
while(matcher.find()) {
System.out.println(matcher.group(i));
i++;
}
现在结果是这样的;
`<style>templates/style/color.css</style>
templates/style/style.css`
为什么一个有样式标签而另一个没有样式标签?
可以试试这个:
String text = "<style>templates/style/color.css</style>\n" +
"<style>templates/style/style.css</style>";
Pattern pattern = Pattern.compile("<style>(.+?)</style>");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(text.substring(matcher.start(), matcher.end()));
}
或者:
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
这将从您的字符串中找到所有出现的地方。
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.