-4

Can someone tell me what the syntax for a regex would be that would only allow the following characters:

a-z 
A-Z
0-9
dash
underscore

Additionally the string cannot contain more than 5 numbers.

Thank you in advance for the help!

olehan
  • 1
  • 2
    `\w` covers `[a-zA-Z0-9_]` use `[\w-]`. Now the next point is 5 numbers that is difficult to achieve using regex but possible. – Braj Nov 20 '14 at 14:03
  • extract all the digits from string using `\d` regex pattern and check the count. – Braj Nov 20 '14 at 14:05
  • 3
    `^(?!(.*\d){6})[-\w]*$` - Uses a negative lookahead to prevent more than 5 numbers. – Phylogenesis Nov 20 '14 at 14:07
  • How does that meet your requirements @olehan? It doesn't hold up under testing. Can you provide an example of what you want to match as well as what shouldn't match? – Jay Blanchard Nov 20 '14 at 14:32

2 Answers2

1

The regex you need is

^[a-zA-Z0-9_-]{0,5}$

It matches any combination of the characters up to five characters.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • [Hyphens Escaped?](http://stackoverflow.com/questions/9589074/regex-should-hyphens-be-escaped) @Braj – Jay Blanchard Nov 20 '14 at 14:25
  • And I am not sure the OP specified their requirements properly @Braj. If you look at the comments above you'll see another regex that "doesn't work" against the "requirements". Seems we're all guessing here. – Jay Blanchard Nov 20 '14 at 14:33
0

several possibilities:

~\A(?:[a-z_-]*[0-9]){0,5}[a-z_-]*\z(?<=.)~i

or

~\A(?!(?:.*[0-9]){6})[\w-]+\z~

The two patterns assumes that the empty string is not allowed.

First pattern:

~                        # pattern delimiter
\A                       # anchor for the start of the string
(?:[a-z_-]*[0-9]){0,5}   # repeat this group between 0 or 5 times (so 5 digits max)
[a-z_-]*                 # zero or more allowed characters
\z                       # end of the string
(?<=.)                   # lookbehind that checks there is at least one character
~
i                        # make the pattern case insensitive

second pattern:

~
\A
(?!                  # negative lookahead that checks there is not
    (?:.*[0-9]){6}   # 6 digits in the string
)  
[\w-]+
\z
~
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125