Java regular expression matching two consecutive c

2019-08-09 17:47发布

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}")) {...}

2条回答
Ridiculous、
2楼-- · 2019-08-09 18:17

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}
查看更多
成全新的幸福
3楼-- · 2019-08-09 18:21

[^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.

查看更多
登录 后发表回答