2

How we can manage regex in Java?

Yes, I did search regex topics, but I think it is strange in Java. What I would like to do is

My team <[email protected]> 

with regex, I would like to get string between < > as [email protected]

Pattern p = Pattern.compile("(.+?)\\<.*?\\>?");

The above one didn't work.

3 Answers 3

5

Since it appears you're dealing with standard format email addresses (RFC 822) you might want to consider using the JavaMail API. It's designed to work with everything within the spec, whereas with regex you might miss some cases. The code for what you want is simple too:

String input = "My team <[email protected]>";
String email = new InternetAddress(input).getAddress();
Sign up to request clarification or add additional context in comments.

Comments

4

Something like this, maybe?

    final Pattern p = Pattern.compile("(.+?)<(.*?)>");
    final Matcher matcher = p.matcher("Foo bar <[email protected]>");
    if (matcher.matches()) {
         System.out.println(matcher.group(2));
    }

Edit: please also see @WhiteFang34's answer below which is a much better approach if you are dealing with email addresses.

7 Comments

Exception in thread "main" java.lang.IllegalStateException: No match found at java.util.regex.Matcher.group(Unknown Source)
Strange, works on java 6 on my machine. EDIT: inside jUnit4 test, that is :)
Really ? what if I do this pattern and matcher in a loop ? does it change any situtation ??
Now it works, was missing the "matcher.matches()" call that was in my jUnit4 assert, code snippet above updated :)
side-note: the first group is not needed, consequently find() can be used with "<(.*?)>", better for loop/multiple e-mails in text; final is also not needed (@Sae1962)
|
4

Actually you need to call the find() method on a Matcher object in order to walk through your string. And as Petri Pellinen stated you should check for the right grouping.

Try the following code:

String str = "My team <[email protected]>  My team <[email protected]> \n " +
    "My team <xxx-yyyy@uucom> My team <[email protected]> " +
    "My team <[email protected]> My team <[email protected]>";

Pattern p = Pattern.compile("\\<(.*?)\\>");
Matcher m = p.matcher(str);

while(m.find()){
   System.out.println(m.group(1));  
}

and check the groups fetched.

Results are:

[email protected]
[email protected]
xxx-yyyy@uucom
[email protected]
[email protected]
[email protected]

cheers!

1 Comment

side-note: there is no need to quote (escape) < and > (no special meaning in Java regular expressions)

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.