Skip to content
Advertisement

How to return a string which matches the regex in Java

Here is a method which returns true/ false for each match. Instead I want to get the matched string if it matches. If it doesn’t matches then don’t return. I can have an If condition to check if its true or false. But my specific question here is, how to return the string if it matches?

private static boolean IsMatch(String s, String pattern) {
        try {
            Pattern patt = Pattern.compile(pattern);
            Matcher matcher = patt.matcher(s);
            return matcher.matches();
        } catch (RuntimeException e) {
        return false;
    }       
}

Advertisement

Answer

How to get the matched string?

Change the method return to String and return the the desired matched group if found.

Pattern patt = Pattern.compile(pattern);
Matcher matcher = patt.matcher(s);
if (matcher.find()) {
    return matcher.group(); // you can get it from desired index as well
} else {
    return null;
}

Update

Use Optional to get the value if matched. Check for Optional.isPresent() before calling Optional.get() to get the value.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement