Reputation: 1271
Environment: Java
I want to match characters between two string, here is an example
foo <bar <[email protected]> xoo <[email protected]>
I need two String: [email protected] and [email protected]
I am using this regex:
<(.*?)>
But this is returning me
bar <[email protected]
and
[email protected]
So basically I want to match characters between two Strings, but I need the internal ones.
Any help is highly appreciated?
Upvotes: 3
Views: 642
Reputation: 95518
Use the following regex:
<([^<>]+)>
The capturing group should return the string you want.
The problem with your regex is that you are failing to take into account the possibility that you could encounter another <
character after the starting <
. Your regex, as it stands, matches <
and then zero or more of any character (non-greedy) followed by >
. But the .*
part will also match another <
. So you want to basically match a string that starts with <
, then only contains characters other than <
or >
, and finally ends with >
.
Here's some sample code:
String s = "foo <bar <[email protected]> xoo <[email protected]>";
Pattern pattern = Pattern.compile("<([^<>]+)>");
Matcher matcher = pattern.matcher(s);
while(matcher.find()) {
System.out.println(matcher.group(1));
}
You can see this in action in Java here.
Upvotes: 3
Reputation: 785126
You can use this negation based regex for matching:
<[^<>]*>
OR using lookarounds to give you emails only:
(?<=<)[^<>]*(?=>)
Upvotes: 3
Reputation: 431
<([^<>]*?)> will do the trick.
Since "." mathces ANYTHIN (also "<" and ">") "bar ". By using "[^<>]" you say anything (like ".") BUT the charecters within the squares - after the hat.
A great site to test your RegEx is http://www.regexr.com/ :)
Upvotes: 1