Regular Expression về thay thế sự có mặt đầu tiên của String trong Java



Miêu tả vấn đề

Cách thay thế sự có mặt đầu tiên của String trong Regex trong Java?

Giải pháp

Ví dụ sau minh họa cách thay thế sự có mặt đầu tiên của String trong Regex bởi sử dụng phương thức replaceFirst() của lớp Matcher trong Java.

import java.util.regex.Matcher;
import java.util.regex.Pattern;public class Main {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("hello");
      String instring = "hello hello hello.";
      System.out.println("initial String: "+ instring);
      Matcher m = p.matcher(instring);
      String tmp = m.replaceFirst("Java");
      System.out.println("String after replacing 1st Match: "
      +tmp);
   }
}

Kết quả

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

initial String: hello hello hello.
String after replacing 1st Match: Java hello hello.

regular_expression_trong_java.jsp