我正在使用java.util.Regex来匹配字符串中的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`
为什么一个带有样式标签而另一个没有样式标签?
答案 0 :(得分:0)
可以试试这个:
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());
}