Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Odd number of occurrences of a char

Tags:

regex

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.

like image 603
tetris11 Avatar asked Apr 24 '12 12:04

tetris11


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1. 1* means any number of ones.

What does 9 mean in regex?

Definition and Usage The [^0-9] expression is used to find any character that is NOT a digit. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [0-9] expression to find any character between the brackets that is a digit.

Is used for zero or more occurrences in regex?

A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used.


2 Answers

The following regex should work.

\b[bc]*a(([bc]*a){2})*[bc]*\b
like image 168
sch Avatar answered Sep 19 '22 18:09

sch


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");
            }
        }
like image 24
ant Avatar answered Sep 18 '22 18:09

ant