My entire carrier is linked to Java. I have been working in Java for 15 years and I still love it. I currently develop NextReports application My Personal Blog My NextReports Blog NextReports Site Mihai has posted 35 posts at DZone. You can read more from them at their website. View Full User Profile

How useful are Java regular expressions to you?

11.23.2012
| 3035 views |
  • submit to reddit

Java regular expressions are a powerful tool you can use in so many occasions. This post does not intend to make you learn about regular expressions, but to show some real use cases when such patterns can help. We can organize this use cases in following categories:

1. String replacement

a) Remove all letters from a string that contains only digits and letters.

s.replaceAll("[^0-9]", "") 
or the equivalent
s.replaceAll("\\D", "")
b) Replace all non-ASCII characters or '?' with space
s.replaceAll("[^\\p{ASCII}]|[\\?]", "")


2. Validation

To validate a string regarding a pattern you have to do the following:

Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(stringToTest);
return matcher.matches();  

You can validate a lot of things, such as:
  
a) Number :  A string that is composed from 4 digits

\\d{4} 

b) Phone number : A string (7 digits in a row) or (3 digits followed by a white space or a dash and then another 4 digits)

\\d{3}([-\\s])?\\d{4} 

c) Mail : A mail pattern accepting user@company.com or user@company.com.eu

^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$

d) Password : Regular expression to validate a password that has at least one digit, at least one lower letter, at least one upper letter and at least one special character from @#$% (and can contain or not any other characters like _,& and so on). Password must be between 6 and 20 characters.

(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20}


3. Extract data by grouping parts of your regular expression

Some examples can be to  extract the data between some tags of a html file or to extract some properties values from a json string, like in following example where we want all the names:

"\"name\":\"([a-zA-Z ]+)\",\"phone\":
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(stringToTest);
while(matcher.find()) {                    String name = matcher.group(1);   // do something with your read value }

If you want, please share with the community other useful usages you had with regular expressions during development.

Published at DZone with permission of its author, Mihai Dinca - Panaitescu.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)