regex
Simple validation example
In this example we shall show you how to make a simple validation of a String, using a Matcher against a specified Pattern. To make a simple String validation one should perform the following steps:
- Create a new Pattern, by compiling to it a regular expression. The regular expression constructed here is the word “Java” followed by a space character and one digit. In order to do so, use
compile(String regex)
API method of Pattern. - Use
matcher(CharSequence input)
API method of Pattern to create a Matcher that will match the given String input against this pattern. - Use
find()
API method of Matcher to try to find the next subsequence of the String input sequence that matches the pattern. The method returns true if, and only if, a subsequence of the input sequence matches this matcher’s pattern. In the example the given in input contains the word “Java” followed by a space character and the digit 5, so the method returns true,
as described in the code snippet below.
Note that the compile(String regex)
API method of Pattern might throw a PatternSyntaxException, that indicates a syntax error in the regular-expression pattern. The application exits if this exception occurs, with System.exit(0)
API method.
package com.javacodegeeks.snippets.core; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class Main { public static void main(String args[]) { Pattern pattern = null; try { pattern = Pattern.compile("Java \\d"); } catch (PatternSyntaxException e) { e.printStackTrace(); System.exit(0); } String str = "I love Java 5"; Matcher m = pattern.matcher(str); System.out.println("result=" + m.find()); } }
Output:
result=true
This was an example of how to make a simple validation of a String, using a Matcher against a Pattern in Java.