正则表达式30分钟入门系列之6

2025-11-08 02:28:12

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;

   }

}

正则表达式30分钟入门系列之6

2、上面待匹配的字符串中,\W部分并没有字母、数字、下划线

应该全部匹配

执行下看看结果:

Output:

true

与预期一致

OK

正则表达式30分钟入门系列之6

3、刚才不是说\W与字母、数字、下划线都不匹配

更改下代码

Code:

List<String> input = Arrays.asList("HelloY!", "Hello7!", "Hello_!");

正则表达式30分钟入门系列之6

4、根据上面的解析

上面的三个字符串应该都不匹配

执行下看看结果

Output:

Hello[\W]! is not match  HelloY!!

Hello[\W]! is not match  Hello7!!

Hello[\W]! is not match  Hello_!!

false

与预期一致

OK

正则表达式30分钟入门系列之6

5、细心的tx已经发现[\\w\\W]代码所有可能的字符

来测一下

更改代码

Code:

String regexStr = "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_!");

正则表达式30分钟入门系列之6

6、按照上面的解析

应该是全部匹配

执行下看看结果

Output:

true

与预期一致

OK

正则表达式30分钟入门系列之6

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢