多语言展示
当前在线:1225今日阅读:39今日分享:10

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

正则表达式也是一种语言,在解析字符串领域独领风骚。本文分享关于正则表达式中两个最常用的关键字\W及相关用法[\w\W]
工具/原料
1

IntelliJ IDEA

2

Java

3

Regular expressions

方法/步骤
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 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 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 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

6

按照上面的解析应该是全部匹配执行下看看结果Output:true与预期一致OK

推荐信息