Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Introduction

Regarding cybersecurity, password validation is essential in protecting users’ accounts. Moreover, using regular expressions (regex) in Java provides a powerful and dynamic way of imposing specific standards for password complexity.

In this tutorial, we’ll delve into utilizing the regex for Java-based password validation processes.

2. Criteria for a Robust Password

Before we get into the code, we’ll establish what makes a strong password. An ideal password should:

  • Have eight characters or more
  • Include a capital letter
  • Use at least one lowercase letter
  • Consists of at least one digit
  • Need to have one special symbol (i.e., @, #, $, %, etc.)
  • Doesn’t contain space, tab, etc.

3. Implementation in Java

3.1. Regular Expression-based Password Validation

Regular expressions, or regex, are useful tools in Java that allow searching, matching, and transforming strings based on certain patterns. In the same context, regex adopts a more static approach for password validation that operates with the help of predefined regular expressions.

The following Java regular expression encapsulates the specified requirements:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@#$%^&+=]).{8,}$

Breaking down its components:

  • ^: indicates the string’s beginning
  • (?=.*[a-z]): makes sure that there is at least one small letter
  • (?=.*[A-Z]): needs at least one capital letter
  • (?=.*\\d): requires at least one digit
  • (?=.*[@#$%^&+=]): provides a guarantee of at least one special symbol
  • .{8,20}: imposes the minimum length of 8 characters and the maximum length of 20 characters
  • $: terminates the string

Let’s use regex for password validation:

@Test
public void givenStringPassword_whenUsingRegulaExpressions_thenCheckIfPasswordValid() {
    String regExpn = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,20}$";

    Pattern pattern = Pattern.compile(regExpn, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(password);

    assertTrue(matcher.matches());
}

Here, we characterize the regExpn regular expression, which specifies certain rules for a password. Besides, we compile the regExpn regular expression into a pattern using Pattern.compile() method and then create a matcher for the given password through the pattern.matcher() method.

Lastly, we utilize the matcher.matches() method to determine if the password meets the regExpn regular expression.

3.2. Dynamic Password Validation

This approach presents a dynamic password verification method that enables the creation of a pattern based on different attributes. This technique involves an arbitrary pattern, including a minimum/maximum length, special symbols, and other elements.

Let’s implement this approach:

@Test
public void givenStringPassword_whenUsingDynamicPasswordValidationRules_thenCheckIfPasswordValid() {
    boolean result = false;
    try {
        if (password != null) {
            String MIN_LENGTH = "8";
            String MAX_LENGTH = "20";
            boolean SPECIAL_CHAR_NEEDED = false;

            String ONE_DIGIT = "(?=.*[0-9])";
            String LOWER_CASE = "(?=.*[a-z])";
            String UPPER_CASE = "(?=.*[A-Z])";
            String SPECIAL_CHAR = SPECIAL_CHAR_NEEDED ? "(?=.*[@#$%^&+=])" : "";
            String NO_SPACE = "(?=\\S+$)";

            String MIN_MAX_CHAR = ".{" + MIN_LENGTH + "," + MAX_LENGTH + "}";
            String PATTERN = ONE_DIGIT + LOWER_CASE + UPPER_CASE + SPECIAL_CHAR + NO_SPACE + MIN_MAX_CHAR;

            assertTrue(password.matches(PATTERN));
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        fail("Exception occurred: " + ex.getMessage());
    }
}

Here, we first ensure that the password doesn’t equal null before carrying on with validation. Then, the method determines validation criteria through individual strings, stipulating such issues as the presence of one digit, one lower case symbol, and an upper case letter with optionally special characters.

Moreover, we use the MIN_MAX_CHAR string to establish the password’s minimum and maximum length limits, using defined standards MIN_LENGTH and MAX_LENGTH. Afterward, the composite PATTERN string concatenates all the indicated prerequisites to develop a dynamic validation pattern.

Finally, we utilize the assertTrue(password.matches(PATTERN)) method to verify the password’s compliance with the dynamically created pattern. If exceptions occur during validation, the test is considered failed; details of the exception are printed for debugging purposes.

This approach provides the flexibility to set password validation rules by changing parameters, which makes it appropriate for different validators.

4. Conclusion

In summary, Java regular expressions are a reliable mechanism for performing text validation and manipulation, particularly when it involves the application of strong password security.

Hence, in this article, we give a concise step-by-step guide for constructing an appropriate regular expression to validate passwords, providing the foundation for alteration that can increase safety during user account creation.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW