问题
I am trying to construct a pattern in order to use in validation.
My goal is to have the first character to be a letter or a number, the rest anyhing.
i.ex:
- A'r4nd0m!
- 9!h3ll0.
- b1llin6s
I thought of: [a-zA-Z0-9_/][.*]++
What would be the solution?
Thank you!
回答1:
As I’ve commented, a letter or a number is [\pL\pN]
. Therefore a string beginning with one of those would match the pattern
/^[\pL\pN]/
回答2:
If the first number is a number or letter, you have ^[A-Za-z0-9]
. (The ^
matches the beginning of the string.) For the rest to be anything, a simple .*
will suffice, so you have ^[A-Za-z0-9].*
.
回答3:
You can trim down your regex a little:
^[a-zA-Z0-9].*
Starts with letter/number, can be of any length or any characters after.
回答4:
You must anchor your regex at the start of the string, using /^/
. Your character class [a-zA-Z0-9_/]
also matches an underscore and a slash: is this what you intend? Also, [.*]++
matches one or more dots or stars, and the trailing +
superfluously duplicates the quantifier.
Since the remainder of the string can be "anything" there is no point in matching it, and
/^[A-Za-z0-9]/
will do fine.
来源:https://stackoverflow.com/questions/9295589/regex-must-start-with-a-letter-or-a-number-but-the-rest-can-be-anything