Regex match words Java
This regular expression can be used to validate that a given string contains only characters in it or extract two words from a given string.
Simple word match
The regular expression to match only words looks like this (including compound words):
Pattern.compile("^\\b(?:\\w|-)+\\b$")
Enter a text in the input above to see the result
Example code in Java:
import java.util.regex.Pattern;
import java.util.regex.MatchResult;
import java.util.Arrays;
public class Main {
public static void main(String []args) {
// Validate word
boolean isMatch = Pattern.compile("^\\b(?:\\w|-)+\\b$")
.matcher("word")
.find();
System.out.println(isMatch); // prints true
// Extract words from a string
String[] matches = Pattern.compile("\\b(?:\\w|-)+\\b")
.matcher("Hello, world!")
.results()
.map(MatchResult::group)
.toArray(String[]::new);
System.out.println(Arrays.toString(matches)); // prints [Hello,world]
}
}