Regex to check non-repetition of a set of characters

前端 未结 8 938
无人共我
无人共我 2020-12-19 12:47

Suppose I have the set of characters [ABC]. I\'m looking for a regex that would match any permutation of the superset except the empty set, i.e.



        
8条回答
  •  抹茶落季
    2020-12-19 13:16

    Here's my version:

    \b(?=[ABC]{1,3})([ABC]{1})(?:(?!\1)([ABC]{1})(?:(?!\1)(?!\2)[ABC]{1})?)?\b
    

    Logic:

    • \b: look for a word boundary
    • (?=[ABC]{1,3}): lookahead to see if there is a string of length = 3 with values of only A, B, C
    • ([ABC]{1}): match the first character then optionally
    • (?!\1)([ABC]{1}): check if the next character is not the same as previously matched - if it's not, match it and optionally
    • (?!\1)(?!\2)[ABC]{1}: check if the next character is not the same as previously matched char 1 or 2 - if it's not, match the character

    I tested it against this input, so it seems quite reliable:

    AABCC BBCC AB BC AC CB CA BA A B C ABC ACB BAC BCA CAB CBA AAA ABB AAA BBC AA


    EDIT:

    As you mentioned the character set can be larger I would follow the PS advice in your question and do this the following way:

    • introduce chars array which will hold each character in the allowed set (split the string into chars)

    • get an array of inputStrings (split the input string on whitespace or whatever else required)

    • for each string in inputStrings {

    • check if the string.length <= inputStrings.length
    • tryMatch each character in the list against the current input and save the number of matches found in a matches list
    • check if the matches list contains any entries and then if all entries == 1 or 0 }

提交回复
热议问题