Reputation: 9372
I would like to test if a string is empty or if it only contain specific characters, each at most once.
Example:
Given $valid = 'ABCDE'
, the following strings are:
$a = ''; // valid, empty
$b = 'CE'; // valid, only contains C and E, each once
$c = 'AZ'; // invalid, contains Z
$d = 'DAA'; // invalid, contains A twice
Any quick way of doing this, (possibly) using regex?
Upvotes: 1
Views: 70
Reputation: 520978
We can try using the following regex pattern:
^(?!.*(.).*\1)[ABCDE]{0,5}$
Here is an explanation of the regex:
^ from the start of the string
(?!.*(.).*\1) assert that the same letter does not repeat
[ABCDE]{0,5} then match 0-5 letters
$ end of the string
Sample PHP script:
$input = "ABCDE";
if (preg_match("/^(?!.*(.).*\1)[ABCDE]{0,5}$/", $input)) {
echo "MATCH";
}
The negative lookahead (?!.*(.).*\1)
works by checking if it can capture any single letter, and then also find it again later on in the string. Let's take the OP's invalid input DAA
. The above negative lookahead would ffail when it matches and captures the first A
, and then sees it again. Note carefully that lookarounds can have their own capture groups.
Upvotes: 4