Java正则表达式 – 查找没有元音的字符串

我有一个单词列表,我必须输出没有元音的单词数。 到目前为止我有这个

String matchString = "[^aeiou]" for(String s: list) if(s.matches(matchString.toLowerCase())) { System.out.println(s); numMatches++; } 

我更担心reg表达式是错误的。

这个对我有用:

 [^aeiou]+$ 

你也应该小写字符串,而不是表达式:

 if (s.toLowerCase().matches(matchString)) 

将正则表达式更改为

 [^aeiou]+ ^-- important part 

测试字符串是否来自一个或多个非元音字符 。 目前你只是在检查搅拌是否来自一个不是你的角色。

您还可以通过在开始时添加(?i)标志来使正则表达式不区分大小写。 这样,正则表达式中使用的字符将代表其大小写

 (?i)[^aeiou]+ 

看起来你把正则表达式放在小写而不是你实际测试的字符串。 你要

 if (s.toLowerCase().matches(matchString)){...} 

另外,我相信你的正则表达式应该是"[^aeiou]*" ,所以你可以匹配单词中的所有字符。

import java.util.regex。*;

公共课元音{

 public static void main(String[] args) { String s = "hello"; int count = 0; Pattern p = Pattern.compile("[aeiou]"); Matcher m = p.matcher(s); while (m.find()) { count++; System.out.println(m.start() + "...." + m.group()); } System.out.println("number of vowels found in the string ="+count); } 

}