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.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button