Java match any set of characters
To match any set of characters using regular expressions in Java, you can use square brackets []
to specify a character class.
For example, to match any uppercase or lowercase letter, you can use the following regular expression pattern:
String pattern = "[a-zA-Z]";
This pattern matches any character that is either an uppercase or lowercase letter. You can add additional characters to the set by placing them inside the square brackets.
To use this regular expression to match any set of characters, you can use the Matcher
class:
String input = "Hello, World!"; Pattern pattern = Pattern.compile("[a-zA-Z]"); Matcher matcher = pattern.matcher(input); while (matcher.find()) { System.out.println("Match found: " + matcher.group()); }
In the example above, the regular expression pattern is compiled into a Pattern
object. The Matcher
class is then used to search the "input" string for any matches to the pattern. The find()
method is called in a loop to find all matches in the string. When a match is found, the group()
method is called to retrieve the matched character.
Note that you can use other predefined character classes, such as \d
to match any digit, or \s
to match any whitespace character. You can also use ranges to match any set of characters within a specified range, such as [0-9]
to match any digit from 0 to 9.