Java regex alphanumeric characters
To match alphanumeric characters using regular expressions in Java, you can use the \w
character class. The \w
character class matches any alphanumeric character (letters and digits) as well as underscore (_).
For example, to match any string containing only alphanumeric characters, you can use the following regular expression pattern:
String pattern = "^\\w+$";
This pattern matches any input string containing one or more alphanumeric characters, and no other characters. The ^
character at the beginning of the pattern specifies that the match should start at the beginning of the input string, and the $
character at the end of the pattern specifies that the match should end at the end of the input string.
To use this regular expression to match an input string, you can use the Matcher
class:
String input = "HelloWorld123"; Pattern pattern = Pattern.compile("^\\w+$"); Matcher matcher = pattern.matcher(input); if (matcher.find()) { System.out.println("Match found: " + matcher.group()); } else { System.out.println("No match found."); }
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. If a match is found, the group()
method is called to retrieve the matched substring.
Note that you can use other character classes to match specific types of characters, such as \d
to match digits, \s
to match whitespace characters, or [^abc]
to match any character that is not a, b, or c.