I need help building a regular expression for preg_match
according these rules:
Legal examples :
Not legal example :
Edit: I remove 4 rule with neigbor chars '_'\\'-'\\'.'
please help me.
Thanks
Try this regular expression:
^[A-Za-z0-9]+([-_.][A-Za-z0-9]+)*$
This matches any sequence that starts with at least one letter or digit ( ^[A-Za-z0-9]+
) that may be followed by zero or more sequences of one of -
, _
, or .
( [-_.]
) that must be followed by at least one letter or digit ( [A-Za-z0-9]+
).
Try this:
^[\p{L}\p{N}][\p{L}\p{N}_.-]*[\p{L}\p{N}]$
In PHP:
if (preg_match(
'%^ # start of string
[\p{L}\p{N}] # letter or digit
[\p{L}\p{N}_.-]* # any number of letters/digits/-_.
[\p{L}\p{N}] # letter or digit
$ # end of the string.
%xu',
$subject)) {
# Successful match
} else {
# Match attempt failed
}
Minimum string length: Two characters.
Well, for each of your rules:
First and last letter/digit:
^[a-z0-9]
and
[a-z0-9]$
empty space not allowed (nothing is needed, since we're doing a positive match and don't allow any whitespace anywhere):
Only letters/digits/-/_/.
[a-z0-9_.-]*
No neighboring symbols:
(?!.*[_.-][_.-])
So, all together:
/^[a-z0-9](?!.*[_.-][_.-])[a-z0-9_.-]*[a-z0-9]$/i
But with all regexes, there are multiple solutions, so try it out...
Edit: for your edit :
/^[a-z0-9][a-z0-9_.-]*[a-z0-9]$/i
You just remove the section for the rule you want to change/remote. it's that easy...
对于提供的示例,这似乎很好用: $patt = '/^[a-zA-Z0-9]+([-._][a-zA-Z0-9]+)*$/';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.