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...
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP