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 !!

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial