正则表达式30分钟入门系列之6
1、\W:这个关键字代表 非一个字母、数字或下划线与\w相反的意义了先来看看测试的脚手架代码:Code:package chapter4;import 枣娣空郅java.util.Arrays;import java.util.List;import java.util.regex.Matcher;import java.util.regex.Pattern;public class RegexStudyDemo { public static void main(String[] args) { String regexStr = "Hello[\\W]!"; List<String> input = Arrays.asList("Hello汉!", "Hello !", "Hello !", "Hello\b!", "Hello\t!", "Hello\"!" , "Hello\r!", "Hello\f!", "Hello\n!", "Hello-!"); System.out.println(isMatch(input, regexStr)); } private static boolean isMatch(List<String> inputs, String regexStr) { boolean result = true; for (String input : inputs) { Pattern pattern = Pattern.compile(regexStr); Matcher matcher = pattern.matcher(input); if (matcher.matches()) { continue; } System.out.println(String.format("%s is not match %s!", regexStr, input)); result = false; } return result; }}
2、上面待匹配的字符串中,\W部分并没有字母、数字、下划线应该全部匹配执行下看看结果:Output:true与预期一致OK
3、刚才不是说\W与字母、数字、下划线都不匹配更改下代码Code:List<String> input = Arrays.asList("HelloY!", "Hello7!", "Hello_!");
4、根据上面的解析上面的三个字符串应该都不匹配执行下看看结果Output:Hello[\W]! is not match HelloY!!Hello[\W]! is not match Hello7!!Hello[\W]! is not match Hello_!!false与预期一致OK
5、细心的tx已经发现[\\w\\W]代码所有可能的字符来测一下更改代码Code:String rege旌忭檀挢xStr = "Hello[\\w\\W]!";List<String> input = Arrays.asList("Hello汉!", "Hello !", "Hello !", "Hello\b!", "Hello\t!", "Hello\"!", "Hello\r!", "Hello\f!", "Hello\n!", "Hello-!", "HelloY!", "Hello7!", "Hello_!");
6、按照上面的解析应该是全部匹配执行下看看结果Output:true与预期一致OK