This is a tip for those situations where you need to find a value into a String using a regular expression (regex).
If the regular expression is a big deal or in case we forget the syntax, is always good to have this site in your browser Bookmark: http://www.regular-expressions.info/reference.html
To assemble this simple example, I used only the Eclipse and Java 6.
Well, let's go to the code!
First of all, I created a class and I called StringUtil.java. After I created a static methodthat takes two parameters, the first: Regular Expression and the second: string that contains the values that I want to look, in this case we'll search for emails.
The method Compile of Class Pattern will compile the regular expression and then the Class Matcher will find for values in the variable text.
So, was added an while for search in the string, looking for values, when found, the method group() will return the string.
public static String getEmailInText(String regex, String text) {
if (text==null || regex==null || regex.isEmpty() || text.isEmpty()) {
return "";
}
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
String listEmail = "";
while (matcher.find()) {
listEmail += matcher.group() + " ";
}
return listEmail.trim();
}
Now, we gonna understand what I've done at the Main() method.
In the start of the regular expression, we begin with syntax \\w+, what means find a group of characters which need be followed by an @.
The "+" symbol means what one or more characters can be showed. The same rule is valid for the next syntax \\ww+\\. Which will group characters, just changing the next literal for “.”.
And in the end of the expression \\w+)*, after ".", will find in the string, searching for characters.
public static void main(String[] args) {
String regex="(\\w+)@(\\w+\\.)(\\w+)(\\.\\w+)*";
String texWithEmail = "In a big text mary@xpto.com.zip.test, could be necessary to find for an e-mail list tom@abc.com and harry@zyx.com";
System.out.println("Emails found: [" + getEmailInText(regex, texWithEmail) + "]");
}
I hope you like the article, feel free to comment, share your experiences.

See the prices for this post in Mr.Bool Credits System below: