How to create a regular expression that takes into account the number of occurrences, but not the appearance of a position?

I want to create a regex that matches the following lines:

A string with all or some of the four characters "A", "B", "C" and "D"

"ABCD" can be performed in any position no more than once. For example, the following is expected:

A,AB,CABD,DC,BDCA,ABC,... 

The following should not match:

 ABA,BB,ABCC,DDAA,AACD... 

Do you have any suggestions for me?

+4
source share
2 answers

This needs to be done (Python syntax):

 if re.match(r""" # Match string having max one each of A, B, C or D. ^ # Anchor to start of string. (?=[^A]*(?:A[^A]*)?$) # Assert zero or one A max. (?=[^B]*(?:B[^B]*)?$) # Assert zero or one B max. (?=[^C]*(?:C[^C]*)?$) # Assert zero or one C max. (?=[^D]*(?:D[^D]*)?$) # Assert zero or one D max. [ABCD]+ # One or more of [ABDC]. \Z # Anchor to end of string. """, text, re.VERBOSE): # Successful match at the start of the string else: # Match attempt failed 

Here is the JavaScript version:

 var re = /^(?=[^A]*(?:A[^A]*)?$)(?=[^B]*(?:B[^B]*)?$)(?=[^C]*(?:C[^C]*)?$)(?=[^D]*(?:D[^D]*)?$)[ABCD]+$/; if (re.test(text)) { // Successful match } else { // Match attempt failed } 
+2
source

Invert your test. Try:

([ABCD]).*\1

That is, find one of the 4 characters that should be followed by an arbitrary set of characters (even empty), followed by the character that you mapped in the first place.

If you have a match, the string does not meet your expectations.

+1
source

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


All Articles