有没有办法在Java中写一个正则表达式,用于查找一个字符串中特定字符(比如 "a")的数量是否为奇数?我已经使用了更冗长的代码来实现此功能,主要使用了以下方法:
如果以字符串
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;
}
如果以字符串
"jsadaajaaikadjasl"
作为参数传递,则返回true,因为它包含7个"a"
。是否有一种更优雅的方法只使用正则表达式
并像下面这样检查呢?Pattern p = Pattern.compile(...);
Matcher m = p.matcher(s);
if(m.matches())
return true;
?
!s.replaceAll("[^*a[^a]a[^a]*|[^a]+", "").isEmpty();
- Joop Eggen