Java正则表达式模式匹配在第二次出现时不起作用
我正在使用java。util。正则表达式以匹配字符串中的正则表达式。该字符串基本上是一个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`
为什么一个有样式标签,另一个没有样式标签
# 1 楼答案
你可以试试这个:
或: