Character Class \p{javaWhitespace} จับคู่ตัวอักษรที่ Character.isWhitespace(char) คืนค่า true คือ whitespace ตาม Java definition (กว้างกว่า \s)
ตัวอย่าง 1: นับ whitespace
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string");
String input = sc.nextLine();
String regex = "[\\p{javaWhitespace}]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Number of whitespace characters: " + count);
}
}
ผลลัพธ์
Enter a string: hello welcome to tutorialspoint
Number of whitespace characters: 3
ตัวอย่าง 2: หาสตริงที่ประกอบด้วย whitespace เท่านั้น
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
String regex = "^\\p{javaWhitespace}+$";
Scanner sc = new Scanner(System.in);
System.out.println("Enter 5 input strings: ");
String[] input = new String[5];
for (int i = 0; i < 5; i++) {
input[i] = sc.nextLine();
}
Pattern p = Pattern.compile(regex);
System.out.println("Strings with only whitespace characters:");
for (int i = 0; i < 5; i++) {
Matcher m = p.matcher(input[i]);
if (m.matches()) {
System.out.println(m.group());
}
}
}
}
ผลลัพธ์
Enter 5 input strings:
Raju
RAMU
rahman
radha
SUnDar*
Strings with only whitespace characters:
(ไม่มี output เพราะไม่มีสตริงที่เป็น whitespace อย่างเดียว)
อธิบาย
\p{javaWhitespace}=Character.isWhitespace()ตรวจสอบตาม Java spec- รวม: space ( ), tab (\t), newline (\n), carriage return (\r), form feed (\f), vertical tab (\v), และ Unicode space characters อื่นๆ
- ต่างจาก
\s(POSIX) ที่รวมแค่ [ \t\n\x0B\f\r] - Java whitespace กว้างกว่า: รวม Unicode spaces เช่น EM SPACE (U+2003), EN SPACE (U+2002), IDEOGRAPHIC SPACE (U+3000) ฯลฯ
ตัวอย่างที่ 2 - หมายเหตุ
ตัวอย่างในต้นฉบับมีข้อผิดพลาด: output แสดง "RAMU" แต่ regex เป็น whitespace only - น่าจะเป็น typo ในต้นฉบับ ผลลัพธ์จริงควรไม่มี output (เช่นตัวอย่างด้านบน)
เปรียบเทียบ Whitespace Definitions
| Character | \s (POSIX) | \p{javaWhitespace} | Character.isWhitespace() |
|---|---|---|---|
| Space (U+0020) | ✓ | ✓ | ✓ |
| Tab (U+0009) | ✓ | ✓ | ✓ |
| LF (U+000A) | ✓ | ✓ | ✓ |
| CR (U+000D) | ✓ | ✓ | ✓ |
| FF (U+000C) | ✓ | ✓ | ✓ |
| VT (U+000B) | ✓ | ✓ | ✓ |
| NBSP (U+00A0) | ✗ | ✓ | ✓ |
| EM SPACE (U+2003) | ✗ | ✓ | ✓ |
| IDEOGRAPHIC SPACE (U+3000) | ✗ | ✓ | ✓ |
เมื่อไหร่ใช้ \p{javaWhitespace}?
- ต้องการความสอดคล้องกับ Java
Character.isWhitespace() - ประมวลผลข้อความหลายภาษา (i18n) ที่มี Unicode spaces
- Trim/validate ตาม Java standard