假设以下是带有特殊字符的字符串。String str = "test*$demo";
检查特殊字符。Pattern pattern = Pattern.compile("[^A-Za-z0-9]");
Matcher match = pattern.matcher(str);
boolean val = match.find();
现在,如果布尔值“ val”为true,则表示字符串中包含特殊字符。if (val == true)
System.out.println("字符串中包含特殊字符。");
示例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("字符串中包含特殊字符。");
else
System.out.println("特殊字符不在字符串中。");
}
}
输出结果String: test*$demo
字符串中包含特殊字符。
以下是另一个具有不同输入的示例。
示例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("字符串中包含特殊字符。");
else
System.out.println("特殊字符不在字符串中。");
}
}
输出结果String: testdemo
特殊字符不在字符串中。..