Java 中檢查字串不包含某些字元


假設以下字串包含特殊字元。

String str = "test*$demo";

檢查特殊字元。

Pattern pattern = Pattern.compile("[^A-Za-z0-9]");
Matcher match = pattern.matcher(str);
boolean val = match.find();

現在,如果 bool 值“val”為真,則意味著字串中包含特殊字元。

if (val == true)
System.out.println("Special characters are in the string.");

示例

 線上演示

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String []args) {
      String str = "test*$demo";
      System.out.println("String: "+str);
      Pattern pattern = Pattern.compile("[^A-Za-z0-9]");
      Matcher match = pattern.matcher(str);
      boolean val = match.find();
      if (val == true)
         System.out.println("Special characters are in the string.");
      else
         System.out.println("Special characters are not in the string.");
   }
}

輸出

String: test*$demo
Special characters are in the string.

以下是具有不同輸入的另一個示例。

示例

 線上演示

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String []args) {
      String str = "testdemo";
      System.out.println("String: "+str);
      Pattern pattern = Pattern.compile("[^A-Za-z0-9]");
      Matcher match = pattern.matcher(str);
      boolean val = match.find();
      if (val == true)
         System.out.println("Special characters are in the string.");
      else
      System.out.println("Special characters are not in the string.");
   }
}

輸出

String: testdemo
Special characters are not in the string...

更新於: 27-Jun-2020

3K+ 瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.