Java Regex to check Min/Max Length of Input Text

In this java regex tutorial, we will learn to test whether length of input text is between some minimum and maximum limit.

All Programming languages provide efficient way to check the length of text. However, using regular expressions to check text length can be useful in some situations, particularly when length is only one of multiple rules that determine whether the subject text fits the desired pattern.

For example, 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.

Regex : ^[A-Z]{1,10}$

List<String> names = new ArrayList<String>();
names.add("LOKESHGUPTAINDIA");  //Incorrect
names.add("LOKESH123");  //Incorrect

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

Pattern pattern = Pattern.compile(regex);

for (String name : names)
	Matcher matcher = pattern.matcher(name);



I will advise to play with above simple regular expression to try more variation.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Java Regex to check Min/Max Length of Input Text”

  1. Hello Friend
    need one help, I am using this ^([a-zA-Z][a-zA-Z0-9_]*){8,30}$
    I am matching with SushanT007 and getting false
    Its picking 8 chanracter. I want to it will pickup both character and number
    could you please help here


Leave a Comment


A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.