11

Found nothing specific to my problem in searches:

I have an Alphabet {a,b,c}, where I need to produce a set of strings that have an odd number of a's.

Valid: ababaccccc baaaccccc cab caabaaac

InValid: baac caacccb caabbbaac

Attempt:

\b[bc]*a{3}[bc]*\b but this is very limited.

Cœur
  • 37,241
  • 25
  • 195
  • 267
tetris11
  • 817
  • 2
  • 11
  • 27

4 Answers4

9

The following regex should work.

\b[bc]*a(([bc]*a){2})*[bc]*\b
sch
  • 27,436
  • 3
  • 68
  • 83
2

If you need solution without regex i.e. Java:

String arr[] = {"ababaccccc",  "baaaccccc" , "caabaaac", "baac", "caacccb", "caabbbaac"};   

for (String string : arr) {
            int counter = 0;
            for (int i = 0; i < string.length(); i++) {
                if (string.charAt(i) == 'a') {
                    counter++;
                }
            }
            if ((counter & 1) == 0) {
                System.out.println(string + " is invalid");
            } else {
                System.out.println(string + " is valid");
            }
        }
ant
  • 22,634
  • 36
  • 132
  • 182
  • why not have a boolean variable called valid, which starts as false and changes state whenever we encounter the character 'a': String arr[] = {"ababaccccc", "baaaccccc" , "caabaaac", "baac", "caacccb", "caabbbaac"}; for (String string : arr) { bool valid = false; for (int i = 0; i < string.length(); i++) { if (string.charAt(i) == 'a') { valid = !valid; counter++; } } if (valid) { System.out.println(string + " is valid"); } else { System.out.println(string + " is invalid"); } } – Sergiu Mindras Dec 15 '14 at 14:59
0

Wouldn't it be easier to

  1. split the input string on whitespace
  2. count the 'a's in every element
  3. based on the outcome of count accept or reject ?
Joanna Derks
  • 4,033
  • 3
  • 26
  • 32
0

An example for python regex: This returns match if there is an odd number of m in sequence

'(m|(m(m{2})+))$'

And this returns the match if there is an odd number of m in sequence or with h's between the m's

'(h*mh*|(h*mh*(h*mh*m)+)h*)$'

Now you can make other combinations from this idea :)