เมธอด split(String regex) ของคลาส String แยกสตริงเป็น array ตาม delimiter ที่ระบุ (เป็น regex) หากไม่พบ delimiter จะคืนค่า array ที่มีแค่สตริงต้นฉบับ
ตัวอย่าง: Split ด้วยคำว่า " to "
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class SplitFixedSequence {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("D:\\sample.txt"));
StringBuilder sb = new StringBuilder();
while (sc.hasNextLine()) {
sb.append(sc.nextLine());
}
String source = sb.toString();
String[] result = source.split(" to ");
System.out.println(Arrays.toString(result));
}
}
ผลลัพธ์
[Tutorials Point originated from the idea that there exists a class of readers who respond better, on-line content and prefer, learn new skills at their own pace from the comforts of their drawing rooms.]
จุดสำคัญ: split() รับ Regex ไม่ใช่ Plain String
อักขระพิเศษใน Regex ต้อง escape:
| ต้องการ split ด้วย | Regex ที่ต้องใช้ |
|---|---|
| . | \\. |
| | | \\| |
| ( ) | \\( \\) |
| [ ] | \\[ \\] |
| { } | \\{ \\} |
| \\ | \\\\ |
| $ | \\$ |
| ^ | \\^ |
| * | \\* |
| + | \\+ |
| ? | \\? |
ตัวอย่าง: Split ด้วยอักขระพิเศษ
String str = "a.b|c(d)e[f]g{h}i";
// split ด้วย . | ( ) [ ] { }
String[] parts = str.split("[.|()\\[\\]{}]"); // ใช้ character class
// ผลลัพธ์: [a, b, c, d, e, f, g, h, i]
วิธี Split แบบ Plain String (ไม่ใช่ Regex) - Java 8+
ใช้ Pattern.quote() เพื่อ escape อัตโนมัติ
import java.util.regex.Pattern;
String delimiter = "to"; // หรือ ".*", "(test)", ฯลฯ
String[] parts = source.split(Pattern.quote(delimiter));
Split แบบ Limit (จำกัดจำนวนชิ้น)
String str = "a,b,c,d,e";
str.split(",", 3); // [a, b, c,d,e] - จำกัด 3 ชิ้น
str.split(",", -1); // [a, b, c, d, e] - เก็บทุกชิ้น รวม trailing empty
str.split(","); // [a, b, c, d, e] - default (ตัด trailing empty ออก)
Best Practices
- Pre-compile Pattern หาก split ซ้ำหลายครั้ง:
Pattern p = Pattern.compile(regex); p.split(input) - ใช้
Pattern.quote()สำหรับ delimiter แบบ fixed string - หลีกเลี่ยง split ใน loop ใหญ่ๆ - ใช้ StringTokenizer หรือ manual parsing แทน
- Java 12+ มี
String.split(Pattern)overload