Reputation: 856
I wrote a method to extract name and email address from a given string. I am using following regex expression
"FROM: (?: ?([^ ]*)?\\s)?(?:<?(.+@[^>]+)>?)"
In the above expression "FROM: " is kind of flag which comes before required name and email address. The issue is when I check this regex in online tool then it works fine as shown below.
However, if I use this regex expression in the java 8 code then it only matches when the input string is only "FROM: aaa bbb [email protected]". If the input string has an extra character at start or end of string then it doesn't match. Following is the code
public void extractNameAndEmail(String input) {
if(input == null)
return;
String reg = "FROM: (?: ?([^ ]*)?\\s)?(?:<?(.+@[^>]+)>?)";
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(input);
if(matcher.matches()) {
System.out.println(matcher.group());
}
}
Any suggestion what I am missing here would be very helpful.
Upvotes: 0
Views: 123
Reputation: 106
From java documentation: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Matcher.html
A matcher is created from a pattern by invoking the pattern's matcher method. Once created, a matcher can be used to perform three different kinds of match operations:
- The matches method attempts to match the entire input sequence against the pattern.
- The lookingAt method attempts to match the input sequence, starting at the beginning, against the pattern.
- The find method scans the input sequence looking for the next subsequence that matches the pattern.
As you can see, matches
method will only return true
if the whole regex matches the data.
In you case, you are trying to find the part of the data matching the regex, so you should use the find
method.
So, your code should look like this:
public void extractNameAndEmail(String input) {
if(input == null)
return;
String reg = "FROM: (?: ?([^ ]*)?\\s)?(?:<?(.+@[^>]+)>?)";
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println(matcher.group());
}
}
Upvotes: 2