2

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

1 Answer 1

5

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));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.