-1

Regex: ^[a-zA-Z]+(?:[\\s'.-]*[a-zA-Z]+)*$

I want add another validation on it i.e. minimum 3 characters and maximum 15 characters.

Regex: ^([a-zA-Z]+(?:[\\s'.-]*[a-zA-Z]+)*){3,28}$

This is validating for minimum characters but not for maximum characters.

Any help is appreciated.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
S Kumar
  • 555
  • 7
  • 21
  • 4
    You've wrapped the entire pattern in `{3,28}`, so the **entire pattern** may repeat between 3 and 28 times. If you want to enforce the length, just do that outside of the regex: `srt.length() >= 3 && str.length() <= 15` – Michael Jan 29 '19 at 12:50
  • 2
    Alternatively to what Michael propose (which you should really consider, especially if performances matter), you could use a positive lookahead such as `^(?=.{3,15}$)([a-zA-Z]+(?:[\\s'.-]*[a-zA-Z]+)*){3,}$` – Aaron Jan 29 '19 at 12:55
  • Could you give us some example inputs please? – aBnormaLz Jan 29 '19 at 13:01
  • 1
    What you need is `^(?=.{3,15}$)[a-zA-Z]+(?:[\\s'.-]*[a-zA-Z]+)*$` – revo Jan 29 '19 at 13:03

1 Answers1

3

You could use a positive lookahead (?=.{3,15}$ to check if the string has a length from 3 - 15 characters.

Because the minimum length of the string is 3 and has to start and end with a-zA-Z you can combine the 2 character classes in the middle in this case.

I think your pattern could be simplified by removing the repetition of the group due to the positive lookahead to:

^(?=.{3,15}$)[a-zA-Z]+[\\s'.a-zA-Z-]*[a-zA-Z]+$

Explanation

  • ^ Start of the string
  • (?=.{3,15}$) Positive lookahead to assert the lenght 3-15
  • [a-zA-Z]+ Match 1+ times a lower/upper case char a-z
  • [\\s'.a-zA-Z-]* Charater class to match any of the listed 0+ times
  • [a-zA-Z]+ Match 1+ times a lower/upper case char a-z
  • $ End of the string

See the Java demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • Thanks for the answer! This resolves the issue of length validation but it does not match name "ffff's ffffffffff" as it was matching earlier and this seems to be because of adding positive lookahead. – S Kumar Jan 30 '19 at 09:54
  • @SKumar The string `ffff's ffffffffff` is of length 17, which is longer than the maximum of 15. – The fourth bird Jan 30 '19 at 10:00
  • That's correct. Thanks! Was considering it for 28, My bad!. – S Kumar Jan 30 '19 at 14:51