To match consonants in a string using a regular expression in Java, you can use the following pattern:
"[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]"
This pattern uses a character class to match any uppercase or lowercase consonant.
Here is an example of how you can use this regular expression to find all consonants in a string in Java:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String input = "Hello, world!"; String pattern = "[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]"; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(input); while (m.find()) { System.out.println("Found consonant: " + m.group()); } } }
In this example, we use the Pattern.compile
and Matcher.matcher
methods to create a Pattern
object and a Matcher
object for the regular expression. We then use the Matcher.find
method in a loop to find all occurrences of the pattern in the input string, and print each matching consonant to the console.