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

Java Regex: ตรวจสอบสตริงมีตัวอักษร/ตัวเลขอย่างน้อย 1 ตัว

Regex สำหรับตรวจสอบสตริงที่มีตัวอักษรหรือตัวเลข (alphanumeric) อย่างน้อย 1 ตัว:

"^.*[a-zA-Z0-9]+.*$"

อธิบาย

ส่วนRegexความหมาย
Prefix^.*เริ่มต้น สตริง 0+ ตัวอักษรใดๆ
Core[a-zA-Z0-9]+ตัวอักษร/ตัวเลข อย่างน้อย 1 ตัว
Suffix.*$สิ้นสุด สตริง 0+ ตัวอักษรใดๆ

ตัวอย่าง 1: ใช้ Pattern/Matcher

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

public class Example {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string");
        String input = sc.nextLine();
        String regex = "^.*[a-zA-Z0-9]+.*$";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        
        if (matcher.matches()) {
            System.out.println("Given string is valid");
        } else {
            System.out.println("Given string is not valid");
        }
    }
}

ผลลัพธ์

Enter a string: ###test123$$$
Given string is valid

Enter a string: ####$$$$
Given string is not valid

ตัวอย่าง 2: ใช้ String.matches()

import java.util.Scanner;

public class Example {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string");
        String input = sc.nextLine();
        String regex = "^.*[a-zA-Z0-9]+.*$";
        boolean result = input.matches(regex);
        
        if (result) {
            System.out.println("Valid match");
        } else {
            System.out.println("Invalid match");
        }
    }
}

ผลลัพธ์

Enter a string: ###test123$$$
Valid match

Enter a string: ####$$$$
Invalid match

วิธีง่ายกว่า (ไม่ใช้ Regex)


// Java 8+
boolean hasAlnum = input.chars().anyMatch(Character::isLetterOrDigit);

// Apache Commons Lang
boolean hasAlnum = StringUtils.isAlphanumeric(input); // ต้องมี alphanumeric อย่างน้อย 1 และไม่มีอื่น
// หรือ
boolean hasAlnum = StringUtils.containsAny(input, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");

ข้อแตกต่าง: matches() vs find()

  • matcher.matches() / String.matches() - ต้องจับคู่ ทั้งสตริง
  • matcher.find() - หา substring** ที่จับคู่

ตัวอย่างนี้ใช้ matches() เพราะ regex มี ^.* ... .*$ ครอบทั้งสตริง

Regex แบบย่อ (Equivalent)

  • [a-zA-Z0-9] → \p{Alnum} (POSIX) หรือ [\p{IsAlphabetic}\p{IsDigit}] (Unicode)
  • ^.*[a-zA-Z0-9]+.*$ → .*[a-zA-Z0-9].* (เพราะ matches() ต้องจับคู่ทั้งสตริง)
  • Simplest: input.matches(".*[a-zA-Z0-9].*")