Regex: matching specific characters in any order without occurrence of each character than specified

I have a list of characters, for example. {o, b, c, c, d, o, f}.

If a string contains characters that are not on this list, I do not want this to be a match. If a string contains more occurrences of a character than there are occurrences of that character in this list, I do not want this to be a match.

Characters in a string can occur in any order, and all characters should not appear. The above example "foo"should be a match, but not "fooo".

For example, I narrowed down the above example to (o{0,2}b?c{0,2}d?f?), but that doesn’t quite work, since order matters in this regular expression. I get matching for "oof", but not for "foo".

+4
source share
3 answers

As stated in gview, regex is not the right tool. However, if your regex engine supports lookahead, you can use this:

(?=(?:[^o]*o){0,2}[^o]*$)(?=(?:[^c]*c){0,2}[^c]*$)(?=[^b]*b?[^b]*$)(?=[^d]*d?[^d*]*$)(?=[^f]*f?[^f]*$)^[obcdf]+$

Its a little long but very simple:

The string maps to ^[obcdf]+$(note the use of anchors).

Modes (?=...)are just checks (they follow):

(?=(?:[^o]*o){0,2}[^o]*$)   # no more than 2 o until the end

(?=[^b]*b?[^b]*$) # no more than 1 b until the end

Each subpattern in lookaheads describes an entire line.

+6
source

I do not think regular expression is the right tool for this requirement. I would create a simple array with a list of characters in the white list. If your language has associative arrays, then enter a letter and specify the number of occurrences in the array element.

, .

, :

  • .
+4

Another way might work as well

 # ^(?!(?:.*o){3})(?!(?:.*c){3})(?!(?:.*b){2})(?!(?:.*d){2})(?!(?:.*f){2})[obcdf]+$

 ^                 # BOS
 (?! (?:.* o){3} ) # not more than 2 'o'
 (?! (?:.* c){3} ) # not more than 2 'c'
 (?! (?:.* b){2} ) # not more than 1 'b'
 (?! (?:.* d){2} ) # not more than 1 'd'
 (?! (?:.* f){2} ) # not more than 1 'f'
 [obcdf]+          # can only be these
 $                 # EOS
+2
source

Source: https://habr.com/ru/post/1531820/


All Articles