Reputation: 11
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
Upvotes: 1
Views: 138
Reputation: 336348
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.
Upvotes: 2
Reputation: 165251
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...
Upvotes: 1
Reputation: 5753
This seems to work fine for provided examples: $patt = '/^[a-zA-Z0-9]+([-._][a-zA-Z0-9]+)*$/';
Upvotes: 1
Reputation: 655479
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]+
).
Upvotes: 3