regex: check string for even number of a symbol
Hi,for example "***'asd'asd" is valid, but "asd'asd'asd'asd" is not, for symbol " ' ". I have tried every combination of \w, [...],',+ and nothing...Ideas?
[183 byte] By [
uiga] at [2007-11-27 6:19:23]

boolean isValid(String s, char symbol) {
return ((s.length() - s.replace(""+symbol, "").length()) % 2) == 0;
}
>boolean isValid(String s, char symbol) {
> return ((s.length() - s.replace(""+symbol,
> "").length()) % 2) == 0;
>
what is doing the %2 here, prome' ?
> ...> what is doing the %2 here, prome' ?If there are an even number of char symbol in String s, then s.length() - s.replace(""+symbol, "").length() will also be even. So that number mod 2 will equal zero (and return true).
If you really have to have a regex solution, this should work: if (str.matches("[^']*+(?:'[^']*+'[^']*+)*+"))
{
// it's good
}
But I like prometheuzz' solution better.