Is there any way to write a regular expression
in Java which finds if a String
contains an odd number of a specific character i.e. "a"
? I have done it writing more verbose code, using namely the following method:
public static boolean hasEvenNumber(String s) {
int count = 0;
Pattern p = Pattern.compile("(^a)*(a)");
Matcher m = p.matcher(s);
while (m.find())
count++;
if (count % 2 != 0)
return true;
return false;
}
If for example one passes the String "jsadaajaaikadjasl"
as parameter, then it retuns true, since it contains 7 "a"
. Is there a more elegant way to achieve it using only a regex
and checking it like:
Pattern p = Pattern.compile(...);
Matcher m = p.matcher(s);
if(m.matches())
return true;
?
Just create a pattern that matches an even count like "(?:[^a]*a[^a]*a)*"
the add another occurrence, (?:[^a]*a[^a]*a)*[^a]*a[^a]
. Now if matcher.matches
returns true
you have an odd number of occurrences.
I don't know why you want to use regex here (and I am not sure if I wan't to know) but you can try with [^a]*a([^a]*a[^a]*a)*[^a]*
.
It means
[^a]* # zero or more non-a characters
# (in case string starts with non-a character)
a # one "a" character
([^a]*a[^a]*a)* # two "a" characters preceded by zero or more non-a characters
# (this will match any numbers of "..a..a" "pairs")
[^a]* # zero or more non-a characters
# (in case string ends with non-a character)
In case you would like to match even numbers of a
just remove [^a]*a
from start or regex.
System.out.println("jsadaajaaikadjasl".matches("[^a]*a([^a]*a[^a]*a)*+[^a]*"));
System.out.println("jasadaajaaikadjasl".matches("[^a]*a([^a]*a[^a]*a)*+[^a]*"));
output:
true
false
Instead of regex you could use this simple method which will iterate over all string characters, compare them with searched one and each time when it find match flip boolean
flag from odd
to even
or vice versa.
public static boolean hasOdd(String s, char character) {
boolean response = false;
for (char c : s.toCharArray())
if (c == character)
response = !response;
return response;
}
//...
System.out.println(hasOdd("jsadaajaaikadjasl", 'a'));//true
System.out.println(hasOdd("jasadaajaaikadjasl", 'a'));//false
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