Java Examples - Splitting a String
Advertisements
Problem Description
How to reset the pattern of a regular expression?
Solution
Following example demonstrates how to reset the pattern of a regular expression by using Pattern.compile() of Pattern class and m.find() method of Matcher class.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Resetting { public static void main(String[] args) throws Exception { Matcher m = Pattern.compile("[frb][aiu][gx]").matcher("fix the rug with bags"); while (m.find())System.out.println(m.group()); m.reset("fix the rig with rags"); while (m.find())System.out.println(m.group()); } }
Result
The above code sample will produce the following result.
fix rug bag fix rig rag
The following is another sample example to reset the pattern of a regular expression
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Matc { public static void main(String args[]) { Pattern p = Pattern.compile("\\d"); Matcher mat1 = p.matcher("9652018244"); while (mat1.find()) { System.out.println("\t\t" + mat1.group()); } mat1.reset(); System.out.println("After done resetting the Matcher, it should be like this"); while (mat1.find()) { System.out.println("\t\t" + mat1.group()); } } }
Result
The above code sample will produce the following result.
9 6 5 2 0 1 8 2 4 4 After done resetting the Matcher, it should be like this 9 6 5 2 0 1 8 2 4 4
java_regular_exp.htm
Advertisements