简体   繁体   中英

IndexOutOfBoundsException when using Matcher.find()

This Java program showing me IndexOutOfBoundsException when it tries to invoke group(1) . If I replace 1 with 0 then the whole line is printed.. What do I have to do?

Pattern pattern = Pattern.compile("<abhi> abhinesh </abhi>");
Matcher matcher = pattern.matcher("<abhi> abhinesh </abhi>");
if (matcher.find())
    System.out.println(matcher.group(1));
else
    System.out.println("Not found");

index starts at 0 so use matcher.group(0)

Edit : To match the text between tag use this regex <abhi>(.*)<\\\\/abhi>

This post may shed more light on your question. Confused about Matcher Group .

In short you haven't defined any regular expression grouping to reference an alternate group. You only have the full matching string.

Below if you try adding a grouped regular expression to parse the xml you'll notice 0 has the full string, 1 has the begin tag, 2 has the value, and 3 has the end tag.

Pattern pattern = Pattern.compile("<([a-z]+)>([a-z ]+)</([a-z]+)>");
Matcher matcher = pattern.matcher("<abhi> abhinesh </abhi>");

if (matcher.find()){
    System.out.println(matcher.group(0));//<abhi> abhinesh </abhi>
    System.out.println(matcher.group(1));//abhi
    System.out.println(matcher.group(2));// abhinesh 
    System.out.println(matcher.group(3));//abhi
}else{
    System.out.println("Not found");
}

Try this this regex:

<abhi>(.*)<\\/abhi>

The text you're after will be stored in the first capture group.

Example:

    String regex = "<abhi>(.*)<\\/abhi>";
    String input = "<abhi>foo</abhi>";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(input);
    if (m.find()) {
        System.out.println(m.group(1));
    }

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