3 minutes read

Regular expressions have a very wide scope of application. They're used in text editors and in implementations of programming languages, for parsing and syntax highlighting, for extraction of useful information from files and web sites. In this lesson, we would like to show you an example of a simple yet powerful program using a regular expression for string processing.

Program with a regular expression

Let's consider a program that checks whether the string logins, separated by commas or whitespace, are valid. We want to split them into separate pieces, check each one, and save only the valid logins.

A valid login follows these rules:

  1. It can contain any Latin letter (uppercase or lowercase), digit, underscore (_), or dollar sign ($).

  2. Its length must be at least 5 characters and at most 12 characters.

Here is an example of the implementation:

class CheckLoginProblem {
    public static void main(String[] args) {
        String stringOfLogins = "admin, user, 123, user_123, $sign abc goodLogin";

        /* Split the line of logins by commas or whitespace */
        String[] potentialLogins = stringOfLogins.split("[,\\s]+");

        /* A pattern for valid logins */
        String loginRegex = "[a-zA-Z0-9_$]{5,12}";

        /* A list to store only valid logins */
        List<String> validLogins = new ArrayList<>();

        for (String login : potentialLogins) {
            /* Check each login against the regular expression */
            if (login.matches(loginRegex)) {
                validLogins.add(login);
            }
        }

        System.out.println(validLogins);
    }
}

Remember, the regex "\\s*" is a very useful practical tool for finding whitespace characters. It's preferable to use this shorthand instead of directly typing " ".

Let's run our program and check the result. The output is:

[admin, user_123, $sign, goodLogin]

As you can see, by using a simple regular expression we can write a quite powerful program for a real-life problem. If you wish, you can rewrite this regex using other special characters.

Conclusion

In this lesson, we've seen a small example of how regular expressions can help us in string processing.
We’ve combined our knowledge of using the matches() method with the power of split() to handle multiple inputs in a single line. Regular expressions help specify exactly what a valid login looks like, and the split() method allows us to isolate each potential login. You can adapt this approach to more complex scenarios, experimenting with different delimiters or stricter requirements for valid logins.

374 learners liked this piece of theory. 9 didn't like it. What about you?
Report a typo