1

I have a requirement to validate username with some special characters in it('-) and white space in it. I am able to achieve this with the help of the following regex -

^[a-zA-z]+([ '-][a-zA-Z]+)*$

But I am unable to add a limit to the maximum number of characters that user can enter say 25 to this particular regex. So can any one please explain how to do the same for the above regex? Thanks.

G.Abhisek
  • 1,034
  • 11
  • 44

2 Answers2

4

You may add a negative lookahead at the beginning disallowing 26 or more chars:

^(?!.{26})[a-zA-Z]+([ '-][a-zA-Z]+)*$
  ^^^^          ^

You also have a typo [A-z], it must be [A-Z]. See Difference between regex [A-z] and [a-zA-Z].

The negative lookahead (the (?!...) construct above) is anchored at the start of the string (meaning it is placed right after ^), and the length check is performed only once, right before parsing with the main, consuming pattern part.

You can also see more on how a negative lookahead works here.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • I do not know your level of regex knowledge :) so that I can only suggest doing all lessons at [regexone.com](http://regexone.com/), reading through [regular-expressions.info](http://www.regular-expressions.info), [regex SO tag description](http://stackoverflow.com/tags/regex/info) (with many other links to great online resources), and the community SO post called [What does the regex mean](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean). Also, [rexegg.com](http://rexegg.com) is worth having a look at. – Wiktor Stribiżew Aug 02 '16 at 06:50
  • Besides, see [regex SO docs](http://stackoverflow.com/documentation/regex/topics). Also, "Mastering Regular Expressions" by Jeffrey E. F. Friedl is a must read if you want to study regexps seriously. – Wiktor Stribiżew Aug 02 '16 at 06:52
  • I am just beginner in Regex and want to learn it from the roots... Thank you. I will go through the links. – G.Abhisek Aug 02 '16 at 06:57
3

Just add a lookahead at the beginning to match only for a max of 25 characters by adding a (?=.{1,25}$).

Your new regex will be: ^(?=.{1,25}$)[a-zA-z]+([ '-][a-zA-Z]+)*$

Anshul Rai
  • 772
  • 7
  • 21