如何使用 Java RegEx 匹配非单词字符?
javaobject oriented programmingprogramming
除英文字母(两种大小写)和数字(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
输入字符串 *&&^# Match occurred
输出 2
输入字符串 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