Phục hồi pattern của Regular Expression trong Java



Miêu tả vấn đề

Cách phục hồi pattern của một Regular Expression trong Java?

Giải pháp

Ví dụ sau minh họa cách phục hồi pattern của một Regular Expression bởi sử dụng phương thức Pattern.compile() của lớp Pattern và phương thức m.find() của lớp Matcher trong Java.

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());
   }
} 

Kết quả

Code trên sẽ cho kết quả sau:

fix
rug
bag
fix
rig 
rag

regular_expression_trong_java.jsp