简体   繁体   中英

Java regex pattern matching not working for second occurrence

I am using java.util.Regex to match regex expression in a string. The string basically a html string.

Within that string I have two lines;

    <style>templates/style/color.css</style>

    <style>templates/style/style.css</style>

My requirement is to get the content inside style tag ( <style> ). Now I am using the pattern like;

String stylePattern = "<style>(.+?)</style>";

When I am trying to get the result using;

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
        }
    }

The result I am getting from output 1 as :

Matcher count : 1 and true

And from output 2 as;

<style>templates/style/style.css</style>

Now, I am just lost after lot of trying that how do I get both lines. I tried many other suggestion in stackoverflow itself, none worked.

I think I am doing some conceptual mistake.

Any help will be very good for me. Thanks in advance.

EDIT

I have changed code as;

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++;
    }

Now the result is like;

  `<style>templates/style/color.css</style>
  templates/style/style.css`

Why one with style tag and another one is without style tag?

Can try this:

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()));
}

Or:

Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
  System.out.println(matcher.group());
}

This will find all occurrences from your string.

   final Pattern pattern = Pattern.compile(regex);
   final Matcher matcher = pattern.matcher(string);
   
   while (matcher.find()) {
       
       System.out.println("Full match: " + matcher.group());
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM