Regex that expresses "at least one non-digit"
I want to validate usernames according to this schema:
- Allowable characters: 开发者_JAVA技巧letters, numbers, hyphen, underscore
- First character must be a letter or a number
- The username cannot be all numbers
This regular expression satisfies 1 and 2 above, but I can't figure out how to satisfy 3:
/^[a-zA-Z\d][\w\-]+$/
(I'm using Ruby, if that's relevant)
Not very efficient, but simple:
/^(?!\d+$)[a-zA-Z\d][\w\-]+$/
The lookahead simply means: "what follows isn't a string of numbers that go on until the end".
If you can go with two passes, a simpler and faster second pass regexp is:
/[^\d]/
This just matches anything that is not a number and it needs to match only one and it terminates early. You don't really need to be strict here because the first pass already rejects non-allowable characters.
Not ideal, but easy: Use a second pass with the regex /^.*[a-zA-Z_\-].*$/
Just ensure it passes both and you'll be fine.
I would use the regex that you need for validation and then something like:
passwd.to_i.to_s.length != passwd.length
to verify that passwd
is not a string of digits after it passes the primary validation.
Yet another way, though it may not perform as well as Max's:
/^[a-z0-9][-\w]*[-_a-z][-\w]*$/i
精彩评论