Java regex to extract text between tags

Viewed 192732

I have a file with some custom tags and I'd like to write a regular expression to extract the string between the tags. For example if my tag is:

[customtag]String I want to extract[/customtag]

How would I write a regular expression to extract only the string between the tags. This code seems like a step in the right direction:

Pattern p = Pattern.compile("[customtag](.+?)[/customtag]");
Matcher m = p.matcher("[customtag]String I want to extract[/customtag]");

Not sure what to do next. Any ideas? Thanks.

8 Answers
    final Pattern pattern = Pattern.compile("tag\\](.+?)\\[/tag");
    final Matcher matcher = pattern.matcher("[tag]String I want to extract[/tag]");
    matcher.find();
    System.out.println(matcher.group(1));

This works for me, use in your main method below Scanner input. Works for Hackerrank "Tag Content Extractor" also.

  boolean matchFound = false;
        Pattern r = Pattern.compile("<(.+)>([^<]+)</\\1>");
        Matcher m = r.matcher(line);

        while (m.find()) {
            System.out.println(m.group(2));
            matchFound = true;
        }
        if ( ! matchFound) {
            System.out.println("None");
        }
        
        testCases--;
Related