如何使用Java RegEx匹配非单词字符?
除英语字母(均为大小写)和数字(0至9)以外的所有字符均被视为非单词字符。您可以使用元字符“\W”来匹配它们。
例子1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//从用户读取字符串
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "^\\W{5}";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
//检索匹配器对象
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
}输出1
Enter a String *&&^# Match occurred
输出2
Enter a String hello Match not occurred
例子2
import java.util.Scanner;
public class RegexExample {
public static void main( String args[] ) {
String regex = "\\W*";
System.out.println("Enter input value: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
boolean bool = input.matches(regex);
if(bool) {
System.out.println("match occurred");
} else {
System.out.println("match not occurred");
}
}
}输出结果
Enter input value: #*** match occurred
热门推荐
9 甄嬛传祝福语简短
10 求助短信生日祝福语简短
11 中班入学祝福语简短大全
12 生日祝福语短句简短霸气
13 弟弟的祝福语简短霸气
14 幼儿节日祝福语大全简短
15 迟到的过年祝福语简短
16 幼儿住院祝福语老师简短
17 薛之谦祝福语简短
18 新年恋人祝福语简短创意