Java regular expression matching two consecutive consonants

不想你离开。 提交于 2019-12-13 01:00:54

问题


I'm trying to match only strings with two consecutive consonants. but no matter what input I give to myString this never evaluates to true, so I have to assume something is wrong with the syntax of my regex. Any ideas?

if (Pattern.matches("([^aeiou]&&[^AEIOU]){2}", myString)) {...}

Additional info:

  • myString is a substring of at most two characters
  • There is no whitespace, as this string is the output of a .split with a whitespace delimiter
  • I'm not worried about special characters, as the program just concatenates and prints the result, though if you'd like to show me how to include something like [b-z]&&[^eiou] in your answer I would appreciate it.

Edit: After going through these answers and testing a little more, the code I finally used was

if (myString.matches("(?i)[b-z&&[^eiou]]{2}")) {...}

回答1:


[^aeiou] matches non-letter characters as well, so you should use a different pattern:

Pattern rx = Pattern.compile("[bcdfghjklmnpqrstuvwxyz]{2}", Pattern.CASE_INSENSITIVE);
if (rx.matches(myString)) {...}

If you would like to use && for an intersection, you can do it like this:

"[a-z&&[^aeiou]]{2}"

Demo.




回答2:


To use character class intersection, you need to wrap your syntax inside of a bracketed expression. The below matches characters that are both lowercase letters and not vowels.

[a-z&&[^aeiou]]{2}


来源:https://stackoverflow.com/questions/28733382/java-regular-expression-matching-two-consecutive-consonants

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!