Regex for no duplicate characters from a limited character pool

前端 未结 3 576
时光取名叫无心
时光取名叫无心 2021-01-04 20:55

Is there a way to write a regex to match a string that only contains certain characters, and never repeats those characters? I already wrote some code using a set to impleme

3条回答
  •  日久生厌
    2021-01-04 21:49

    back referencing can be used. Here comes an example in PHP, which is compatible to Perl regular expressions:

    $string = "A, B, C, AB, AC, B, BC, AABC";
    
    if(preg_match('/([ABC])\1/', $string, $matches)) {
        echo $matches[1] . " has been repeated\n";
    } else {
        echo "OK\n";
    }
    

    In the above pattern ([ABC]) is capturing group which can store one out of the characters A, B or C. \1 references this first capturing group, this makes the pattern matching if one those characters repeats.

提交回复
热议问题