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
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"
}
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With