A list of useful regexp

30 Oct 2011 at 00:00:00 - 0 comment(s)

regexp or in other words regular expression is something you have to regularly use in your applications. I've decided to write this post as a placeholder for regexp I believe are common and useful such as regexp for email validation or some you might use to replace characters in a string. I might write some piece of java code but you can use these regular expression in many other languages.

1. regexp for validating email address

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

But here is actually what I use to validate email address:

  public boolean isValidEmail(String input) {
    Pattern p = Pattern.compile("^\\.|^\\@");
    Matcher m = p.matcher(input);
    if (m.find())
      return false;
    
    p = Pattern.compile("^www\\.");
    m = p.matcher(input);
    
    if (m.find())
      return false;
    
    p = Pattern.compile("[^A-Za-z0-9\\.\\@_\\-~#]+");
    m = p.matcher(input);
    StringBuffer sb = new StringBuffer();
    boolean result = m.find();
    boolean deletedIllegalChars = false;
    
    while(result) {
      deletedIllegalChars = true;
      m.appendReplacement(sb, "");
      result = m.find();
    }
    
    // Add the last segment of input to the new String
    m.appendTail(sb);
    
    input = sb.toString();
    
    if(deletedIllegalChars)
      return false;
    
    return true;
  }

2. regexp to validate username of type test@test

[^@/]+@[^@/]+

3. regexp to replace multiple spaces

\\s+

4. regexp to replace any characters that is not alphanumeric

[^a-zA-Z0-9]


Conclusion

Don't hesitate to propose some more in the comments.

0 comments

Notify me of follow up comments