Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Got Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 1

Tags:

java

regex

I have a string like this

"abc:def"

I need to check if it matches. If yes, I want to apply a regex and retrieve first part of it ("abc").

Here is my try:

Pattern pattern = Pattern.compile(".*:.*");
String  name = "abc:def"
Matcher matcher = pattern.matcher(name);

if (matcher.find()) {
    String group = matcher.group(1);
    System.out.println(group);
}

It gives me

Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 1

like image 759
Mark Avatar asked Dec 25 '22 10:12

Mark


2 Answers

You need to add a capturing group inside your regular expression. This is done by putting what you want to capture inside parentheses:

Pattern pattern = Pattern.compile("(.*):.*"); // <-- parentheses here
String  name = "abc:def";
Matcher matcher = pattern.matcher(name);

if (matcher.find()) {
    String group = matcher.group(1);
    System.out.println(group); // prints "abc"
}
like image 185
Tunaki Avatar answered Jan 17 '23 16:01

Tunaki


You only have a group (0) (full match) because you don't define any capturing groups (enclosed in ( and )) in your regex.

If you change your code to include a capturing group like this

Pattern pattern = Pattern.compile("([^:]*):.*"); 
String  name = "abc:def";
Matcher matcher = pattern.matcher(name);

if (matcher.find()) {
    String fullMatch = matcher.group(0);
    String group = matcher.group(1);
    System.out.println(group);
}

you'll have full match "abc:def" and first group (until first colon) "abc"

like image 35
Jan Avatar answered Jan 17 '23 16:01

Jan