Regex: matching permutations with repeating characters, in which one char cannot occur more than once

The regular expression must match all strings with a length of 2 to 3 characters and contain only A and B ([AB] {2,3}). But also it should just match strings that contain at most one B.

Valid strings:


A.A. Ab
BA
AAA
Aab
ABA
BAA

Is not allowed:

ABB - Two B

Is it possible to achieve this with a single regular expression? I tried something like this:

([AB] {2,3}) (<? = ([B] * A [B] *) {2})

But it does not work in Java because it does not support variable length for the Look-behind group.

Exception in the "main" thread java.util.regex.PatternSyntaxException: the Look-behind group does not have an obvious maximum length near index 28 ([AB] {2,3}) (<? = ([B] * A [B] *) {2})

Any suggestions?

+4
source share
3 answers

You can use a negative lookahead to ensure that the string does not have two B s.

 ^(?!.*B.*B)[AB]{2,3}$ 

Take a look

+4
source

Well, you can simply list the parameters individually:

 ^(A{2,3}|A{1,2}B|ABA|BA{1,2})$ ↑ ↑ ↑ ↑ β”‚ β”‚ β”‚ └─ starting with B β”‚ β”‚ └───── B in the middle β”‚ └───────────── B at the end └──────────────────── only A 
+2
source

Try

 \b(?:A{1,2}B|BA{1,2}|A{2,3}|ABA?)\b 
0
source

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


All Articles