2

I need to validate string with 2 groups which are separated with one space with next rules:

  • Each group needs to be at least 2 character long but less or equal to 15

  • Both groups together can't be more than 20 chars long (not counting space)

  • Groups can only contain letters (that's simple, it's [a-zA-Z])

Following these rules, here are some examples

  • Firstname Lastname (Valid)

  • Somename T (Invalid, 2nd one is <2)

  • Somethingsomettt Here (Invalid, first one is > 15)

  • Somethingsome Somethingsome (Invalid, total > 20)

It'd be simple [a-zA-Z]{2,15} [a-zA-Z]{2,15} if it wasn't for that 2+2<=total<=20 condition.

Is it even possible to limit it this way? If it is - how?

UPDATE Just for the sake of it, resulting regex was supposed to be ^(?=[a-zA-Z ]{5,21}$)[a-zA-z]{2,15} [a-zA-Z]{2,15}$, @vks was closest one to it. Nevertheless, thanks @popovitsj and @Avinash Raj too.

3
  • Why not split on the space in the middle, and separately validate both pieces? This would allow you to trivially check the combined length. Commented Sep 29, 2014 at 18:43
  • Is there a reason you have to do this with one regular expression? Commented Sep 29, 2014 at 18:44
  • 2
    Looks like you have an extra - in the middle of your first character class ([a-z-A-Z]). Commented Sep 29, 2014 at 18:47

3 Answers 3

1
^(?=.{5,21}$)[a-zA-Z]{2,15} [a-zA-Z]{2,15}$

Try this.See demo.

http://regex101.com/r/nA6hN9/30

Sign up to request clarification or add additional context in comments.

Comments

1

This can be done with lookahead. Something like this:

^(?=.{1,20}$)[a-zA-z]{2,14} [a-zA-Z]{2,14}$

13 Comments

Thanks, modified it to ^(?=[a-zA-Z ]{4,21}$)[a-zA-z]{2,15} [a-zA-Z]{2,15}$ which seems to work like I need.
@Flyer did you want to match Somethings Somethings?
@Flyer this is incorrect.the minimum should be 5 not 4.
@Avinash Raj, yeah it should match since both are >=2 <=15, and total is 20 (not counting space)
Who cares 14 or 15... and yours is incorrect too, it matches also tabs and enters instead of just a space in the middle.
|
1

You could try the below regex which uses negative lookahead,

(?!^.{22,})^[a-zA-Z]{2,15} [a-zA-Z]{2,15}$

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.