« Using Javascript and XSLT with ANT | Main | News only nerds would care about... »



March 15, 2005

Fun With Regular Expressions

The Java Development Kit (JDK) has supported Regular Expressions without any external libraries since version 1.4. Regular Expressions are great because they allow you to do things in one line that would normally take many lines of code. Though Regex's (a common nickname for Regular Expressions) can be very cryptic, they are extremely powerful.

If you are new to Regex's, check out this tutorial. Then take a look at some things you can do with Java and Regex's to make your life easier.

Here is a quick example. Suppose I had a String with a sentence containing any number of words, some of which were email addresses. Also, suppose that I wanted to remove all the email addresses for privacy reasons. With Regular Expressions, I can easily (though cryptically) find each email address within the String and replace it with something else using the String.replaceAll() function. Below, strSentence is the example String prefilled with any number of words and email addresses:

strSentence = strSentence.replaceAll("[\\w-]+(?:\\.[\\w-]+)*@(?:[\\w-]+\\.)+[a-zA-Z]{2,7}", "<EMAIL REMOVED FOR PRIVACY>");

In this case, the Regex (unescaped) is: [\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7} - Note that I had to escape all the back slashes in order to put it in a Java String.

Now, my sentence is exactly the same except all email addresses have been replaced with "<EMAIL REMOVED FOR PRIVACY>".

Regex's can also do things like password constraint validation (i.e. your password must be at least 5 characters long and contain a letter and a number), complex pattern matching & replacing and other types of validation such as credit card numbers and SSN's. Struts makes heavy use of Regex's for form validation. Maybe you should too.

Posted by Chuck at March 15, 2005 08:03 PM

Trackback Pings

TrackBack URL for this entry:
http://www.chuckcaplan.com/blog/mt-tb.cgi/14

Comments

Post a comment




Remember Me?