Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set minimum and maximum characters in a regular expression

Tags:

java

regex

I've written a regular expression that matches any number of letters with any number of single spaces between the letters. I would like that regular expression to also enforce a minimum and maximum number of characters, but I'm not sure how to do that (or if it's possible).

My regular expression is:

[A-Za-z](\s?[A-Za-z])+ 

I realized it was only matching two sets of letters surrounding a single space, so I modified it slightly to fix that. The original question is still the same though.

Is there a way to enforce a minimum of three characters and a maximum of 30?

like image 790
CorayThan Avatar asked Mar 08 '13 07:03

CorayThan


People also ask

How do you limit the length of a regular expression?

By combining the interval quantifier with the surrounding start- and end-of-string anchors, the regex will fail to match if the subject text's length falls outside the desired range.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

How range of characters are used in regular expression?

To show a range of characters, use square backets and separate the starting character from the ending character with a hyphen. For example, [0-9] matches any digit. Several ranges can be put inside square brackets. For example, [A-CX-Z] matches 'A' or 'B' or 'C' or 'X' or 'Y' or 'Z'.


2 Answers

Yes

Just like + means one or more you can use {3,30} to match between 3 and 30

For example [a-z]{3,30} matches between 3 and 30 lowercase alphabet letters

From the documentation of the Pattern class

X{n,m}    X, at least n but not more than m times 

In your case, matching 3-30 letters followed by spaces could be accomplished with:

([a-zA-Z]\s){3,30} 

If you require trailing whitespace, if you don't you can use: (2-29 times letter+space, then letter)

([a-zA-Z]\s){2,29}[a-zA-Z] 

If you'd like whitespaces to count as characters you need to divide that number by 2 to get

([a-zA-Z]\s){1,14}[a-zA-Z] 

You can add \s? to that last one if the trailing whitespace is optional. These were all tested on RegexPlanet

If you'd like the entire string altogether to be between 3 and 30 characters you can use lookaheads adding (?=^.{3,30}$) at the beginning of the RegExp and removing the other size limitations

All that said, in all honestly I'd probably just test the String's .length property. It's more readable.

like image 150
Benjamin Gruenbaum Avatar answered Sep 20 '22 18:09

Benjamin Gruenbaum


This is what you are looking for

^[a-zA-Z](\s?[a-zA-Z]){2,29}$ 

^ is the start of string

$ is the end of string

(\s?[a-zA-Z]){2,29} would match (\s?[a-zA-Z]) 2 to 29 times..

like image 44
Anirudha Avatar answered Sep 18 '22 18:09

Anirudha