The Java regex example demonstrates how to use a simple regular expression in Java with an example.
In the example, we have ten words in a list. We check which words match the .even regular expression.
package net.javaguides.corejava.regex;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaRegexExample {
public static void main(String[] args) {
List < String > words = Arrays.asList("One", "Two",
"Three", "Four", "Five", "Six", "Seven", "Maven", "Amen", "eleven");
Pattern p = Pattern.compile(".even");
for (String word: words) {
Matcher m = p.matcher(word);
if (m.matches()) {
System.out.printf("%s -> matches%n", word);
} else {
System.out.printf("%s -> does not match%n", word);
}
}
}
}
Output:
One -> does not match
Two -> does not match
Three -> does not match
Four -> does not match
Five -> does not match
Six -> does not match
Seven -> matches
Maven -> does not match
Amen -> does not match
eleven -> does not match
We compile the pattern. The dot (.) metacharacter stands for any single character in the text.
Comments
Post a Comment