นิพจน์ทั่วไป "[!._,'@?//s]" จะจับคู่เครื่องหมายวรรคตอนและช่องว่างทั้งหมด
ตัวอย่าง
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main( String args[] ) {
String input = "This is!a.sample"text,with punctuation!marks";
Pattern p = Pattern.compile("[!._,'@?//s]");
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("Number of matches: "+count);
}
} ผลลัพธ์
Number of matches: 8
split() เมธอดของคลาส String ยอมรับค่าที่แสดงนิพจน์ทั่วไปและแยกสตริงปัจจุบันออกเป็นอาร์เรย์ของโทเค็น (คำ) โดยถือว่าสตริงระหว่างการเกิดขึ้นของการจับคู่สองรายการเป็นโทเค็นเดียว
ตัวอย่างเช่น หากคุณผ่านช่องว่างเดียว " " เป็นตัวคั่นสำหรับวิธีนี้และพยายามแยกสตริง วิธีนี้จะถือว่าคำระหว่างช่องว่างสองช่องเป็นโทเค็นเดียวและส่งกลับอาร์เรย์ของคำ (ระหว่างช่องว่าง) ในสตริงปัจจุบัน
ดังนั้น หากต้องการแยกสตริงในทุกช่องว่างและเครื่องหมายวรรคตอน ให้เรียกใช้เมธอด split() โดยส่งนิพจน์ทั่วไปที่ระบุข้างต้นเป็นพารามิเตอร์
ตัวอย่าง
import java.util.Scanner;
import java.util.StringTokenizer;
public class RegExample {
public static void main( String args[] ) {
String regex = "[!._,'@? ]";
System.out.println("Enter a string: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
StringTokenizer str = new StringTokenizer(input,regex);
while(str.hasMoreTokens()) {
System.out.println(str.nextToken());
}
}
} ผลลัพธ์
Enter a string: This is!a.sample text,with punctuation!marks@and_spaces This is a sample text with punctuation marks and spaces