Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set maximum length to this regular expression?

Tags:

regex

This validation works well for allowing alphanumeric chars, spaces, and a dash, but I have not been able to set the max length to 23.

Regex: (^\w+\s*(-?)(\s*\w+\s*)(\w+)$){0,23}

The cases I need to pass:

  • Winston1-Salem6
  • Winston-Salem
  • Winston Salem
  • 1-two3
  • word2 with space

Cases I need to fail:

  • -Newberty-Los-
  • 12345678901234567890123444
like image 225
Bazinga Avatar asked May 05 '15 17:05

Bazinga


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.

How will you specify the range of characters using a 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'.

How do I limit the length of a string in Java?

The indexing is done within the maximum range. It means that we cannot store the 2147483648th character. Therefore, the maximum length of String in Java is 0 to 2147483647. So, we can have a String with the length of 2,147,483,647 characters, theoretically.


1 Answers

It may be more convenient to check the length separately, but you can use a lookahead to confirm that the entire expression is between 0 and 23 characters.

(?=^.{0,23}$)(^\w+\s*(-?)(\s*\w+\s*)(\w+)$)

http://rubular.com/r/GVIbG8hDKz

like image 118
Explosion Pills Avatar answered Oct 19 '22 07:10

Explosion Pills