多语言展示
当前在线:1909今日阅读:84今日分享:32

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

正则表达式也是一种语言,在解析字符串领域独领风骚。本文分享关于正则表达式中最常用的关键字{n}、{n,}和{n,m}的用法
工具/原料
1

IntelliJ IDEA

2

Java

3

Regular expressions

方法/步骤
1

正则表达式关键字表示数量的上面已经介绍过“*”、“+”和“?”但是上面的关键字在很多场景不是很合适譬如要匹配一个字符只可能出现3-5次,使用“*”,“+”很明显就不合适了今天就介绍其它几个表示数量的正则表达式关键字{n}:这个关键字表示这样的数量--  前面的字符只能重复n次{n,}:这个关键字表示这样的数量--  前面的字符重复n次或更多次{n,m}:这个关键字表示这样的数量--前面的字符重复n到m次。这样的区间[n,m]先来看看测试的脚手架代码: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\\W]{2}!';        List input = Arrays.asList('Hello汉字!', 'Hello!', 'Hello\n\n!', 'Hello7!');        System.out.println(isMatch(input, regexStr));    }    private static boolean isMatch(List inputs, String regexStr) {        boolean result = true;        Pattern pattern = Pattern.compile(regexStr);        for (String input : inputs) {            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

根据上面对关键字{n}的描述,'Hello[\\w\\W]{2}!'不能匹配字符串'Hello!'和'Hello7!'执行下看看结果Output:Hello[\w\W]{2}! is not match  Hello!Hello[\w\W]{2}! is not match  Hello7!false与预期一致OK

3

有这个关键字'{n}',正则表达式的表现能力是不是又提高了不少啊如果已经确定某种类型的字符可能出现的频繁,譬如2次到4次呢?更改下代码Code:String regexStr = 'Hello[\\w\\W]{2,4}!';List input = Arrays.asList('Hello汉字!', 'Hello三汉字!', 'Hello三个汉字!', 'Hello7!');

4

根据上面的解释,'Hello[\\w\\W]{2,4}!'除'Hello7!'外都可以匹配到执行下看看结果Output:Hello[\w\W]{2,4}! is not match  Hello7!false

5

如果某类字符,只能确定最少会出现几次,最多不限制这种场景正则表达式有没有相应的表达呢有的!细心的tx已经发现了是“{n,}”更改下代码Code:String regexStr = 'Hello[\\w\\W]{2,}!';List input = Arrays.asList('Hello汉字!', 'Hello三汉字!', 'Hello三个汉字!', 'Hello很多个汉字!',        'Hello更多更多个汉字!');

6

根据上面的分析 'Hello[\\w\\W]{2,}!'能匹配上面代码中所有的字符串执行下看看结果Output:true与预期一致OK

推荐信息