TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
- 捕获分组的注意事项:
- 只要使用了括号,就存在捕获分组
- 捕获分组按照开括号出现的从左到右的顺序编号,遇到括号嵌套的情况也是如此
- 如果捕获分组之后存在量词,则匹配结果中,捕获分组保存的是子表达式最后一次匹配的字符串
- 例子:
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- public class GeneralSix {
- 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("匹配结果: " + m.group(0));
- System.out.println("分组1: " + m.group(1));
- System.out.println("分组2: " + m.group(2));
- System.out.println("分组3: " + m.group(3));
- }
- }
- }
复制代码 运行结果:
匹配结果: abacdemasterhappy@163.com
分组1: abacdemasterhappy@163.com
分组2: abacdemasterhappy
分组3: 163.com
String regex = "((\w+)@([\d\.\w]+))";
只是在正则表达式的两端添加了一个( ),此时出现括号嵌套的情况。
依照括号从左到右的顺序,发现,第一个括号对应整个正则表达式,第二个对应用户名正则表达式,第三个括号用于匹配主机名的正则表达式。
再看一个:
- import java.util.regex.*;
- public class GeneralSeven {
- 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("匹配结果: " + m.group(0));
- System.out.println("分组1: " + m.group(1));
- System.out.println("分组2: " + m.group(2));
- //System.out.println("分组3: " + m.group(3));
- }
- }
- }
复制代码 运行结果:
匹配结果: abacdemasterhappy@163.com
分组1: y
分组2: m
将量词作用整个捕获分组。匹配完成之后,捕获分组所保存的就是最后一次它所匹配的文本。
abacdemasterhappy@163.com
相当于匹配用户名的最后一个字符。
捕获分组的事项讲解到此!
不捕获文本的括号
如果正则表达式很复杂,或者需要处理的文本很长,捕获分组会降低效率
作用:仅仅用来对表达式分组,而不把分组捕获的文本存入结果
形式:
(?:...)
注意:不捕获文本的括号,并不是所有语言都有提供,为了增加可读性,并不推荐使用“不捕获文本的括号”。
例子:
- import java.util.regex.*;
- public class GeneralEight {
- public static void main(String[] args) {
- String email = "abacdemasterhappy@163.com";
- String regex = "(?:abacdemasterhappy|admin)@(163.com)";
- Pattern p = Pattern.compile(regex);
- Matcher m = p.matcher(email);
- if(m.find()){
- System.out.println("匹配结果: " + m.group(0));
- System.out.println("分组1: " + m.group(1));
- }
- }
- }
复制代码 运行结果:
匹配结果: abacdemasterhappy@163.com
分组1: 163.com
括号的用途:反向引用
作用:在表达式的某一部分,动态重复之前子表达式所匹配的文本
形式:1
例子:
- public class GeneralNine {
- public static void main(String[] args) {
- String[] strs = new String[] { "< h1>good,good< /h1>", "< h1>bad< /h2>"};
- String regex = "< \w+>[^<]+< /\w+>";
- 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);
- }
- }
复制代码 运行结果:
<h1>good,good</h1>能够匹配正则:<w+>[^<]+</w+>
<h1>bad</h2>能够匹配正则:<w+>[^<]+</w+>
源码下载:http://file.javaxxz.com/2014/10/31/000026734.zip |
|