The use of Java regular expression

Posted by nadz on Sun, 03 Nov 2019 09:50:12 +0100

The java.util.regex package mainly includes the following three classes:

 

Pattern class:

 

The Pattern object is a compiled representation of a regular expression. The Pattern class does not have a common constructor. To create a Pattern object, you must first call its public static compilation method, which returns a Pattern object. This method takes a regular expression as its first parameter.

 

Matcher class:

 

The Matcher object is the engine that interprets and matches the input string. Like the Pattern class, the Matcher does not have a common constructor. You need to call the Pattern object's Matcher method to get a Matcher object.

 

PatternSyntaxException:

 

PatternSyntaxException is a non mandatory exception class that represents a syntax error in a regular expression pattern.

The regular expression. * runoob. * is used in the following example to find if a runoob substring is included in the string:

  

 1 package cc.bcy;
 2 
 3 import java.util.regex.*;
 4 
 5 public class RegexExample 
 6 {
 7     public static void main(String[] args) 
 8     {
 9         String line="This order was placed for QT3000! OK?";
10         String pattern="(\\D*)(\\d+)(.*)";
11         //Establish Pattern object
12         Pattern p=Pattern.compile(pattern);
13         //Establish Matcher object
14         Matcher m=p.matcher(line);
15         if(m.find())
16         {
17             System.out.println("Found value: "+m.group(0));
18             System.out.println("Found value: "+m.group(1));
19             System.out.println("Found value: "+m.group(2));
20             System.out.println("Found value: "+m.group(3));
21         }
22         else
23         {
24             System.out.println("No Match!");
25         }
26         int n=m.groupCount();
27         System.out.println("Altogether"+n+"Capture group");
28     }
29 }
30 /*
31 Found value: This order was placed for QT3000! OK?
32 Found value: This order was placed for QT
33 Found value: 3000
34 Found value: ! OK?
35 There are three capture groups
36 */

Topics: PHP Java Qt