Regular expression matching any subset of a given set?

后端 未结 4 494
面向向阳花
面向向阳花 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 15:06

    Not sure you can get an extended regex to do that, but it's pretty easy to do with a simple traversal of your string.

    You use a hash (or an array, or whatever) to store if any of your allowed characters has already been seen or not in the string. Then you simply iterate over the elements of your string. If you encounter an element not in your allowed set, you bail out. If it's allowed, but you've already seen it, you bail out too.

    In pseudo-code:

    foreach char a in {a1, ..., an}
       hit[a1] = false
    
    foreach char c in string
       if c not in {a1, ..., an} => fail
       if hit[c] => fail
       hit[c] = true
    

提交回复
热议问题