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

Posix Character Class \p{Space} ใน Java Regex

Character class \p{Space} ใช้ match whitespace characters ตาม POSIX definition รวมถึง:

  • \t - Tab (horizontal tab)
  • \n - Newline (line feed)
  • \v - Vertical tab
  • \f - Form feed
  • \r - Carriage return
  • - Space (regular space)
  • \x0B - Vertical tab (alternative notation)

เทียบเท่ากับ \s ใน Java (แต่ \s อาจรวมเพิ่มขึ้นไปในบาง version)

ตัวอย่างที่ 1: นับจำนวน whitespace characters

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SpaceCharacters {
    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{Space}";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        int count = 0;
        while (matcher.find()) {
            count++;
        }
        System.out.println("Number of space characters: " + count);
    }
}

Output

Enter a string
space tab test
Number of space characters: 2

ตัวอย่างที่ 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) {
        // Regex: มี whitespace อย่างน้อย 1 ตัว
        String regex = "^.*\\p{Space}.*$";

        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 spaces:");
        for (int i = 0; i < 5; i++) {
            Matcher m = p.matcher(input[i]);
            if (m.matches()) {
                System.out.println(m.group());
            }
        }
    }
}

Output

Enter 5 input strings:
sample data
hello
welcome to tutorialspoint
12345
ab bc cd da
Strings with spaces:
sample data
welcome to tutorialspoint
ab bc cd da

ความแตกต่าง \p{Space} vs \s vs \h vs \v

Pattern Match หมายเหตุ
\p{Space} POSIX space: space, \t, \n, \v, \f, \r Standard POSIX
\s Whitespace: \p{Space} + \xA0 (no-break space) + อื่นๆ Java default, กว้างกว่า
\h Horizontal whitespace: space, \t, \xA0, etc. Java 8+
\v Vertical whitespace: \n, \v, \f, \r, etc. Java 8+