Set minimum and maximum characters in a regular expression

后端 未结 4 1377
失恋的感觉
失恋的感觉 2020-12-01 14:25

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 enfo

相关标签:
4条回答
  • 2020-12-01 14:38

    you should use

    [a-zA-Z ]{20}
    

    [for allowed characters]{for limit of number of characters}

    0 讨论(0)
  • 2020-12-01 14:39

    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.

    0 讨论(0)
  • 2020-12-01 14:39

    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..

    0 讨论(0)
  • 2020-12-01 14:46

    Actually Benjamin's answer will lead to the complete solution to the OP's question. Using lookaheads it is possible to restrict the total number of characters AND restrict the match to a set combination of letters and (optional) single spaces.

    The regex that solves the entire problem would become

    (?=^.{3,30}$)^([A-Za-z][\s]?)+$
    

    This will match AAA, A A and also fail to match AA A since there are two consecutive spaces. I tested this at http://regexpal.com/ and it does the trick.

    0 讨论(0)
提交回复
热议问题