JavaRegular expressions

Regexes in programs

Using regular expressions it is possible to write simple but powerful programs to process strings in many ways.

As an example, the following program checks the input string is a valid login or no. We suppose a login can contain any Latin letter, a number, the underscore _, and the dollar sign $. The length must be not less than 5 characters and not greater than 12 characters.

There is one additional feature - we should ignore any spaces before and after the input string.

import java.util.Scanner;

class CheckLoginProblem {

    public static void main(String[] args) {

       /* The scanner object to read data from the standard input */
       Scanner scanner = new Scanner(System.in);
       
       /* The common pattern for valid logins */
       String loginRegex = "\\s*[a-zA-Z0-9_$]{5,12}\\s*";

       /* The read string which may be a login */
       String mayBeLogin = scanner.nextLine();

       boolean isLogin = mayBeLogin.matches(loginRegex);

       System.out.println(isLogin);
    }
}

Remember, the regex "\\s*" is very useful in practice to match all spaces.

Let's test the program passing different inputs.

The input-output pair 1:

  testuser7
true

The input-output pair 2:

 test  
false

The input-output pair 3:

      user!!!
false

The input-output pair 4:

$test_user
true

So, using a simple regular expression we can write a quite powerful program. If you would like, you can rewrite the regular expression using other special characters.

How did you like the theory?
Report a typo