Question

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 = "user@email.com";

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
Was it helpful?

Solution

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

String pattern = "([a-z]+)@([a-z]+)\\.([a-z]{3})";
String email = "user@email.com";
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));
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top