查詢字串是否為字母數字的程式。


任何包含數字和字母的詞語都稱為字母數字。以下正則表示式匹配數字和字母的組合。

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

String 類的 matches 方法接受一個正則表示式(以字串形式),並將其與當前字串進行匹配,如果匹配,則此方法返回 true,否則返回 false。

因此,要查詢特定字串是否包含字母數字值 -

  • 獲取字串。
  • 在其上呼叫 match 方法,並傳遞上述正則表示式。
  • 檢索結果。

示例 1

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");
      }
   }
}

輸出

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

示例 2

您還可以編譯正則表示式並使用 java.util.regex 包的類和方法(API)將其與特定字串匹配。以下程式使用這些 API 編寫,並驗證給定字串是否為字母數字。

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(" ");
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      for (String ele : data){
         //creating a 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");
         }
      }
   }
}

輸出

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

更新於: 2019年11月21日

2K+ 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.