要检查字符串是否包含任何特殊字符,Java程序如下所示:
示例import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String[] args){
String my_str="This is a sample only !$@";
Pattern my_pattern = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher my_match = my_pattern.matcher(my_str);
boolean check = my_match.find();
if (check)
System.out.println("Special character found in the string");
else
System.out.println("Special character not found in the string");
}
}
输出结果Special character found in the string
名为Demo的类包含主函数,该函数定义了带有一些特殊字符的字符串。定义了一种模式,该模式使用正则表达式检查字符串是否具有任何特殊字符。定义了一个布尔值,该值检查是否相同。如果Bool的值为true,则打印成功消息,否则,在屏幕上打印一条消息,指出缺少这些特殊字符。