Search code examples
javaregexbackreference

Java - Regex backreferences in array


Is there any way to split a Java String using a regular expression and return an array of backreferences?

As a simple example, say I wanted to pull the username & provider from a simple email address (letters only).

String pattern = "([a-z]+)@([a-z]+)\\.([a-z]{3})";
String email = "[email protected]";

String[] backrefs = backrefs(email,pattern);

System.out.println(backrefs[0]);
System.out.println(backrefs[1]);
System.out.println(backrefs[2]);

This should output

user
email
com

Solution

  • Yes, using the Pattern and Matcher classes from java.util.regex pacakge.

    String pattern = "([a-z]+)@([a-z]+)\\.([a-z]{3})";
    String email = "[email protected]";
    Matcher matcher = Pattern.compile(pattern).matcher(email);
    // Check if there is a match, and then print the groups.
    if (matcher.matches())
    {
        // group(0) contains the entire string that matched the pattern.
        for (int i = 1; i <= matcher.groupCount(); i++)
        {
            System.out.println(matcher.group(i));
        }
    }