正则表达式30分钟入门系列之8
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<String> input = Arrays.asList("Hello汉字!", "Hello!", "Hello\n\n!", "Hello7!"); System.out.println(isMatch(input, regexStr)); } private static boolean isMatch(List<String> 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<String> 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<String> input = Arrays.asList("Hello汉字!", "Hello三汉字!", "Hello三个汉字!", "Hello很多个汉字!", "Hello更多更多个汉字!");
6、根据上面的分析"Hello[\\w\\W]{2,}!"能匹配上面代码中所有的字符串执行下看看结果Output:true与预期一致OK