Java Regex to check Min/Max Length of Input Text

This Java regex example demonstrates how to use Java regular expressions to check the min and max length of the given input text.

Java Regex to check Min/Max Length of Input Text

The following regular expression ensures that text is between 1 and 10 characters long, and additionally limits the text to the uppercase letters A–Z. You can modify the regular expression to allow any minimum or maximum text length or allow characters other than A–Z.
package net.javaguides.corejava.regex;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMinMaxLength {
    public static void main(String[] args) {
        List < String > names = new ArrayList < String > ();

        names.add("RAMESH");
        names.add("JAVAGUIDES");
        names.add("RAMESHJAVAGUIDES"); //Incorrect
        names.add("RAMESH890"); //Incorrect

        String regex = "^[A-Z]{1,10}$";

        Pattern pattern = Pattern.compile(regex);

        for (String name: names) {
            Matcher matcher = pattern.matcher(name);
            System.out.println(matcher.matches());
        }
    }
}
Output:
true
true
false
false

References



Comments