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

โปรแกรมตรวจสอบว่าสตริงเป็น Alphanumeric หรือไม่


คำใดก็ตามที่ประกอบด้วยตัวเลขและตัวอักษรเรียกว่า Alphanumeric Regular Expression ต่อไปนี้จับคู่การรวมกันของตัวเลขและตัวอักษร:

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

เมธอด matches() ของคลาส String รับ regular expression (ในรูปแบบ String) และจับคู่กับสตริงปัจจุบัน หากจับคู่ได้จะคืนค่า true มิฉะนั้นคืนค่า false

ดังนั้น เพื่อตรวจสอบว่าสตริงใดสตริงหนึ่งมีค่า alphanumeric หรือไม่:

  • รับสตริงเข้ามา
  • เรียกเมธอด matches() พร้อม regular expression ด้านบน
  • ดึงผลลัพธ์

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

import java.util.Scanner;

public class AlphanumericString {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input string: ");
        String input = sc.next();
        String regex = "^[a-zA-Z0-9]+$";
        boolean result = input.matches(regex);
        if (result) {
            System.out.println("Given string is alpha numeric");
        } else {
            System.out.println("Given string is not alpha numeric");
        }
    }
}

Output

Enter input string: abc123*
Given string is not alpha numeric

ตัวอย่างที่ 2: ใช้ Pattern และ Matcher (java.util.regex)

คุณยังสามารถคอมไพล์ regular expression และจับคู่กับสตริงเฉพาะได้โดยใช้คลาสและเมธอด (APIs) ของแพ็กเกจ java.util.regex โปรแกรมต่อไปนี้เขียนด้วย APIs เหล่านี้และตรวจสอบว่าสตริงที่ให้มาเป็น alphanumeric หรือไม่

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

public class Test {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter input string: ");
        String input = sc.nextLine();
        String regex = "^[a-zA-Z0-9]+$";
        String data[] = input.split(" ");
        
        // สร้าง Pattern object
        Pattern pattern = Pattern.compile(regex);
        
        for (String ele : data) {
            // สร้าง Matcher object
            Matcher matcher = pattern.matcher(ele);
            if (matcher.matches()) {
                System.out.println("The word " + ele + ": is alpha numeric");
            } else {
                System.out.println("The word " + ele + ": is not alpha numeric");
            }
        }
    }
}

Output

Enter input string: hello* this$ is sample text
The word hello*: is not alpha numeric
The word this$: is not alpha numeric
The word is: is alpha numeric
The word sample: is alpha numeric
The word text: is alpha numeric