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.