TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
- 量词的局限
- 量词只能规定之前字符或字符组的出现次数
- 如果要规定一个字符串的出现次数,必须使用括号(),在括号内填写字符串,在闭括号之后添加量词
- 例子:
- public class GeneralThree {
- public static void main(String[] args) {
- String[] strs = new String[] { "ac", "acc", "accc", "acac","acacac"};
- String regex = "ac+";
- String regex2 = "(ac)+";
- for (String string : strs) {
- if(regexMatch(string,regex)){
- System.out.println(string +"能够匹配正则:" + regex);
- }else{
- System.out.println(string +"不能够匹配正则:" + regex);
- }
- }
- for (String string : strs) {
- if(regexMatch(string,regex2)){
- System.out.println(string +"能够匹配正则:" + regex2);
- }else{
- System.out.println(string +"不能够匹配正则:" + regex2);
- }
- }
- }
- private static boolean regexMatch(String s, String regex) {
- return s.matches(regex);
- }
- }
- 运行结果:
- ac能够匹配正则:ac+
- acc能够匹配正则:ac+
- accc能够匹配正则:ac+
- acac不能够匹配正则:ac+
- acacac不能够匹配正则:ac+
- ac能够匹配正则:(ac)+
- acc不能够匹配正则:(ac)+
- accc不能够匹配正则:(ac)+
- acac能够匹配正则:(ac)+
- acacac能够匹配正则:(ac)+
- 括号的用途:多选结构
- 用途:表示某个位置可能出现的字符串
- 字符组只能表示某个位置可能出现的单个字符,而不能表示某个位置可能出现的字符串
- 形式:
- (...|...),在竖线两端添加各个字符串
- (...|...|...|...)
- 如果希望某个位置出现:this或者that,字符组对此事无能为力的,须采用多选结构。
- 例子:
- public class GeneralFour {
- public static void main(String[] args) {
- String[] strs = new String[] { "this", "that", "thit"};
- String regex = "th[ia][st]";
- for (String string : strs) {
- if(regexMatch(string,regex)){
- System.out.println(string +"能够匹配正则:" + regex);
- }else{
- System.out.println(string +"不能够匹配正则:" + regex);
- }
- }
- }
- private static boolean regexMatch(String s, String regex) {
- return s.matches(regex);
- }
- }
- 这是字符组的匹配结果:
- this能够匹配正则:th[ia][st]
- that能够匹配正则:th[ia][st]
- thit能够匹配正则:th[ia][st]
- 连thit也匹配了,我们希望匹配this和that 这是因为第一个字符组[ia]和第二个字符组[st]没有建立联系。
- 等于i去匹配[ia],t去匹配[st]的错误问题。
- 应该修改规则、使用多选结构:
- String regex = "th(is|at)";
- 或者:String regex = "(this|that)";
- 运行结果:
- this能够匹配正则:(this|that)
- that能够匹配正则:(this|that)
- thit不能够匹配正则:(this|that)
- 将共同部分提取到多选之外,能够提高正则表达式匹配的效率,但是,这个表达式的阅读者,并不见得很容易理解。
- 实际开发的时候,应当根据具体情况来定。
- 推荐使用:String regex = "(this|that)";
- 括号的用途:捕获分组
- 作用:将括号内的表达式捕获的字符串存放到匹配结果中,供匹配完成后访问
- 形式:
- ・使用普通的括号()
- 例子:
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class GeneralFive {
- public static void main(String[] args) {
- String email = "abacdemasterhappy@163.com";
- String regex = "(\w+)@([\d\.\w]+)";
- Pattern p = Pattern.compile(regex);
- Matcher m = p.matcher(email);
- if(m.find()){
- System.out.println("email address is: " + m.group(0));
- System.out.println("username is: " + m.group(1));
- System.out.println("hostname is: " + m.group(2));
- }
- }
- }
- 运行结果:
- email address is: abacdemasterhappy@163.com
- username is: abacdemasterhappy
- hostname is: 163.com
- 所有捕获分组,都是从编号为1开始,编号为0表示默认整个正则表达式所匹配的文本(它不能由捕获分组来加以修改的)。
- 未完待续。。。
复制代码
源码下载:http://file.javaxxz.com/2014/10/30/000028250.zip |
|