Thursday, 18 December 2014

Java Regular Expressions (Regex) with Examples

          A Regular Expression (Regex) defines a search pattern for strings. A search pattern can be as simple as a single character, a fixed string, or a complex expression containing special characters that describe a specific pattern. The pattern defined by a regular expression may match a given string once, multiple times, or not at all.

Regular expressions are commonly used to search, validate, edit, and manipulate text. A Regular Expression is also known as a regex or regexp.

The java.util.regex package was introduced in Java SE 1.4. If you are using an older version of Java, it is recommended that you upgrade to a newer version.

The java.util.regex package contains the following three main classes:

  • Pattern – Represents a compiled regular expression.

  • Matcher – Performs match operations on an input string using a Pattern.

  • PatternSyntaxException – Indicates a syntax error in a regular expression pattern.


  1. Pattern
    The Pattern class represents the compiled version of a regular expression. It does not have a public constructor. Instead, you can create a Pattern object by using its static compile() method and passing the regular expression as an argument.

  2. Matcher
    The Matcher class is the regular expression engine that performs match operations on an input string using a Pattern object. This class also does not have a public constructor. You can obtain a Matcher object by calling the matcher() method on a Pattern object and passing the input string as an argument. The matches() method returns a boolean value indicating whether the entire input string matches the specified regular expression.

  3. PatternSyntaxException
    The PatternSyntaxException class is thrown when the syntax of a regular expression is invalid.


Java Regular Expression Metacharacters

Regular expressions provide several metacharacters, which are special characters used as shorthand for common matching patterns. These metacharacters make regular expressions more powerful and concise.

The ^ and $ metacharacters are known as anchors:

  • ^ – Indicates the beginning of a line or string.

  • $ – Indicates the end of a line or string.

To ensure that the entire input matches a pattern, the regular expression is typically enclosed between ^ and $.

Common Regular Expression Metacharacters

MetacharacterDescription
\dMatches any digit. Equivalent to [0-9].
\DMatches any non-digit. Equivalent to [^0-9].
\sMatches any whitespace character.
\SMatches any non-whitespace character.
\wMatches any word character. Equivalent to [a-zA-Z0-9_].
\WMatches any non-word character. Equivalent to [^\w].
\bMatches a word boundary.
[..]Matches any single character within the brackets.
[^..]Matches any single character not within the brackets.
\tMatches a tab character (U+0009).
\vMatches a vertical tab (U+000B).
+Matches the preceding character one or more times. Equivalent to {1,}.
*Matches the preceding character zero or more times. Equivalent to {0,}.
?Matches the preceding character zero or one time. Equivalent to {0,1}.
.Matches any single character except the newline character.

Examples

Below are some commonly used regular expressions:

Regular ExpressionDescription
^\\d+$Matches one or more numeric digits only.
^\\w+$Matches one or more alphanumeric characters and underscores.
^[a-z0-9_-]{3,16}$Matches lowercase letters, digits, underscores (_), or hyphens (-). The length must be between 3 and 16 characters.
^\\d{5}$Matches exactly five numeric digits.
^(\\d{1,2})-(\\d{1,2})-(\\d{4})$Matches a date in the dd-MM-yyyy format (basic format validation only).

Regular Expression Example

Regular expressions make it possible to find all occurrences of text that match a specific pattern. They can also be used to determine whether an input string matches a pattern by returning a boolean value (true or false).

Regular expressions are widely used for validating user input, such as phone numbers, Social Security numbers, email addresses, web form data, decimal values, numeric values, alphanumeric strings, and many other text formats.

For example, if a regular expression is designed to match only numeric values and the input string satisfies that pattern, the input is considered a valid numeric value. Otherwise, the validation fails.

     import java.util.ArrayList;  
     import java.util.List; 
     public class ValidateDemo {  
            public static void main(String[] args)  {
                    List<String> input = new ArrayList<String>(); 
                    input.add("123");
                    input.add("98HT12");
                    input.add("345") ;
                    for (String numeric : input) { 
                             if (numeric.matches("^\\d+$")) { 
                                      System.out.println("Numerics : " + numeric);  
                             } 
                   } 
            }                
    }

Output:-
      Numerics : 123
      Numerics : 345
      

Syntax Error Validation in Java Using Pattern:-

        public class RegularExpValidation {
                public static void main(String[] args){
                        String valid = RegExpValidation("^\\w{1,$");
                        if(valid != null ){
                               System.out.println(valid);
                        } 
               }

               public static String RegExpValidation(String regPattern){
                       String errorMessage = null;
                       try {
                               Pattern.compile(regPattern);
                       }
                       catch (PatternSyntaxException exception) {
                              errorMessage = exception.getDescription();
                       }
                       return errorMessage;
              }
       }

Output:-
     Illegal repetition

Backslashes in Java with Regular Expressions:-

           In literal Java strings the backslash is an escape character. The literal string "\\" is a single backslash. In regular  expressions, the backslash is also an escape character. The regular expression \\ matches a single backslash. This regular expression as a Java string, becomes "\\\\". That's right: 4 backslashes to match a single one.

The regex \w matches a word character. As a Java string, this is written as "\\w".