Use Regex to Allow 3 Underscores Maximum
'@^([^\W_]*\s){0,3}[^\W_]*$@'
I need to allow 3 underscores.
The above regex matches:
English alphanumeric
3 spaces Doesn't allow underscores Doesn't allow special charactersI want it to match:
English alphanumeric
3 spaces max. Allow 3 underscores max. Doesn't allow special charactersHere is my attempt:
1.
'@^([^\W]*_\s){0,3}[^\W]*$@'
2.
'@^([^\W]*\s){0,3}([^\W]*_){0,3}[^\W]*$@'
Both of my attempts don't work.
I use the regex in php (preg_match function) ... No specific order.
if(preg_match('@^([^\W_]*\s){0,3}[^\W_]*$@', $_POST['txt_username_reg']))
Data match:
james_arden 20
james arden 20 James_arden_20_doneData don't match:
hello james arden done 20 (reason: 4 spaces)
what_is_your_name_done (reas开发者_C百科on: 4 underscores) testing123? (reason: special chars)This matches any string containing 3 or less underscores:
^[^_]*(_[^_]*){0,3}$
And this matches any string containing exactly 3 underscores:
^[^_]*(_[^_]*){3}$
EDIT
To support Arabic letters, try something like this:
'/^[^_]*(_[^_]*){0,3}$/u'
note the use of the u
modifier:
u (PCRE8)
This modifier turns on additional functionality of PCRE that is incompatible with Perl. Pattern strings are treated as UTF-8. This modifier is available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32. UTF-8 validity of the pattern is checked since PHP 4.3.5.
-- http://php.net/manual/en/reference.pcre.pattern.modifiers.php
There's no need to use a regular expressions, just use substr_count
:
$lessThan3Underscores = substr_count($input, '_') <= 3;
If there is some absurd reason why you must use an regular expression (which will be harder to read and therefore, harder to maintain), match against
^[^_]*(_[^_]*){0,3}$
I'd just like to post a separate answer for the sake of a different approach.
Rather than build a complex regex that keeps count, just allow infinitely many underscores... then run another regex after that and make sure there is at most 3 underscores. Can greatly simplify more complicated conditions.
PS. Got beaten to it by @phihag
精彩评论