sign up! Channels Courses
 

Alessandra Lima Aguiar - MrBool Space


20 last updates Alessandra Lima Aguiar

Article - How to find a String with Regular Expression in Java

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.

Listing 1 : search and return e-mails that are located on a String.

[CODE] 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(); } [/CODE]

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.

Listing 2 : Defining a regex

[CODE] 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) + "]"); } [/CODE]

I hope you like the article, feel free to comment, share your experiences.

-->">
4/17/2012 10:54:00 PM





 

alessandra@gmail.com

Systems Analyst and Developer at IBM. Graduated in Information System at UNISA (University of Santo Amaro) and an MBA in Software Technology at USP (Universidade de São Paulo), operates in the IT market since 1999 and is currently focused on development web in JAVA.
Archive updates
 2012

Stats:
Total posts: 1