英文:
Ensure a string contains specific characters, each at most once
问题
我想测试一个字符串是否为空,或者是否只包含特定字符,每个字符最多出现一次。
示例:
给定$valid = 'ABCDE',以下字符串是:
$a = ''; // 有效,空字符串
$b = 'CE'; // 有效,只包含C和E,每个字符出现一次
$c = 'AZ'; // 无效,包含Z
$d = 'DAA'; // 无效,包含A两次
有没有快速的方法来做到这一点,(可能)使用正则表达式?
英文:
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?
答案1
得分: 4
我们可以尝试使用以下正则表达式模式:
^(?!.*(.).*)[ABCDE]{0,5}$
以下是对正则表达式的解释:
^从字符串的开头开始(?!.*(.).*\1)断言相同的字母不会重复出现[ABCDE]{0,5}然后匹配0到5个字母$字符串的结尾
示例 PHP 脚本:
$input = "ABCDE";
if (preg_match("/^(?!.*(.).*)[ABCDE]{0,5}$/", $input)) {
    echo "MATCH";
}
负向前瞻 (?!.*(.).*\1) 的作用是检查是否可以捕获任何单个字母,然后在字符串中再次找到它。让我们以 OP 的无效输入 DAA 为例。当它匹配并捕获第一个 A,然后再次看到它时,上述负向前瞻将失败。请注意,前瞻可以有自己的捕获组。
英文:
We can try using the following regex pattern:
^(?!.*(.).*)[ABCDE]{0,5}$
Here is an explanation of the regex:
^                    from the start of the string
    (?!.*(.).*)    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("/^(?!.*(.).*)[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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论