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.
$ 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.
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.
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.
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.
The following regex should work.
\b[bc]*a(([bc]*a){2})*[bc]*\b
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With