Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Java String replace(), replaceFirst() และ replaceAll() แตกต่างกันอย่างไร?

ทั้งสามเมธอดอยู่ใน Class String ใช้สำหรับแทนที่ข้อความ แตกต่างกันที่ Regex Support และ Scope (First/All)

1. replace(CharSequence target, CharSequence replacement)

  • ไม่ใช้ Regex (Literal String Replacement)
  • แทนที่ ทุก Occurrence
  • มี Overload สำหรับ char ด้วย
String text = "Hello Tutorialspoint. At Tutorialspoint we learn.";
// แทนที่ "Tutorialspoint" -> "TP" (Literal, ไม่ใช่ Regex)
String result = text.replace("Tutorialspoint", "TP");
// Result: "Hello TP. At TP we learn."

// Character Version
String result2 = text.replace('T', '#');
// Result: "Hello #utorialspoin#. A# #utorialspoin# we learn."

2. replaceAll(String regex, String replacement)

  • ใช้ Regex Pattern
  • แทนที่ ทุก Match
  • Replacement String รองรับ Group Reference ($1, $2)
String text = "Hello Tutorialspoint. At Tutorialspoint we learn.";
// Word Boundary \b ป้องกัน Partial Match
String result = text.replaceAll("\\bTutorialspoint\\b", "TP");
// Result: "Hello TP. At TP we learn."

// ใช้ Group Reference
String phone = "081-234-5678";
String masked = phone.replaceAll("(\\d{3})-(\\d{3})-(\\d{4})", "$1-$2-####");
// Result: "081-234-####"

3. replaceFirst(String regex, String replacement)

  • ใช้ Regex Pattern
  • แทนที่ Match แรกสุดเท่านั้น
String text = "Hello Tutorialspoint. At Tutorialspoint we learn.";
// แทนที่แค่ครั้งแรก
String result = text.replaceFirst("Tutorialspoint", "TP");
// Result: "Hello TP. At Tutorialspoint we learn."

ตารางเปรียบเทียบ

Method Regex? Scope Use Case
replace(target, repl) No (Literal) All แทนที่ข้อความคงที่ เร็วที่สุด
replaceAll(regex, repl) Yes All Pattern-based Replace, Group Ref
replaceFirst(regex, repl) Yes First Only แทนที่แค่ครั้งแรก

Performance Note

  • replace(CharSequence, CharSequence) เร็วที่สุด (No Regex Compilation)
  • replaceAll/First Compile Regex ทุกครั้ง -> ใช้ Pattern.compile() แยกไว้ถ้าเรียกซ้ำ

ข้อผิดพลาดทั่วไป

// ผิด: คิดว่า replace() ใช้ Regex
"1.5".replace(".", ","); // OK: "1,5" (Literal Dot)

// ถ้าต้องการ Regex Dot (Any Char) ต้องใช้ replaceAll
"1.5".replaceAll(".", ","); // ผล: ",,," (Dot Match ทุก Char!)
// ถูกต้อง:
"1.5".replaceAll("\\.", ","); // Escape Dot -> "1,5"

สรุป

  • แทนที่ข้อความคงที่ -> replace() (เร็ว, ไม่ต้อง Escape)
  • แทนที่ด้วย Pattern/Regex -> replaceAll() (All) หรือ replaceFirst() (First)
  • ทั้งหมด Case-Sensitive และ คืน String ใหม่ (Original Immutable)