Regular expression matching any subset of a given set?

后端 未结 4 400
面向向阳花
面向向阳花 2021-01-13 14:38

Is it possible to write a regular expression which will match any subset of a given set of characters
a1 ... an ?
I.e. it should match any string whe

4条回答
  •  不思量自难忘°
    2021-01-13 14:59

    Can't think how to do it with a single regex, but this is one way to do it with n regexes: (I will usr 1 2 ... m n etc for your as)

    ^[23..n]*1?[23..n]*$
    ^[13..n]*2?[13..n]*$
    ...
    ^[12..m]*n?[12..m]*$
    

    If all the above match, your string is a strict subset of 12..mn.

    How this works: each line requires the string to consist exactly of:

    • any number of charactersm drawn fromthe set, except a particular one
    • perhaps a particular one
    • any number of charactersm drawn fromthe set, except a particular one

    If this passes when every element in turn is considered as a particular one, we know:

    • there is nothing else in the string except the allowed elements
    • there is at most one of each of the allowed elements

    as required.


    for completeness I should say that I would only do this if I was under orders to "use regex"; if not, I'd track which allowed elements have been seen, and iterate over the characters of the string doing the obvious thing.

提交回复
热议问题