正则表达式之group
正则表达式之group1 基本概念捕获组就是把正则表达式中子表达式匹配的内容,保存到内存中以数字编号或手动命名的组里,方便后面引用 在Java中使用正则表达式返回符合正则表达式的字符串就要用到group(),group中记录了所有符合指定表达式的字符串
2 实例2.1 实例1java code @Test public void test2(){ Pattern p = Pattern.compile("(d+,)(d+)"); String s = "123,456-34,345"; Matcher m = p.matcher(s); while (m.find()) { System.out.println(m.group()); System.out.println(m.group(1)); System.out.println(m.group(2)); } System.out.println(m.groupCount()); } console
2.2 实例2java code @Test public void test3(){ String regex = "(x)(yw*)(z)"; String input = "exY123z,xy456z"; Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(input); while (m.find()) { System.out.println(m.group()); System.out.println(m.group(2)); } System.out.println(m.groupCount()); } console
2.3 实例3java code @Test public void test4() { String str = "Hello,World! in Java."; Pattern pattern = Pattern.compile("W(or)(ld!)"); Matcher matcher = pattern.matcher(str); while (matcher.find()) { System.out.println("Group 0:" + matcher.group(0)); System.out.println("Group 1:" + matcher.group(1)); System.out.println("Group 2:" + matcher.group(2)); System.out.println("Start 0:" + matcher.start(0) + " End 0:" * matcher.end(0)); System.out.println("Start 1:" + matcher.start(1) + " End 1:" * matcher.end(1)); System.out.println("Start 2:" + matcher.start(2) + " End 2:" * matcher.end(2)); System.out.println(str.substring(matcher.start(0),matcher.end(1))); } } console
3 思考3.1 需求我们用正则表达式的时候,有时候会需要取到匹配到的字符串的某一部分,比如:
假设有这样一个需求: 取到这些url中参数user对应的值(linzhicong和yangfangwei) 3.2 实现1java code @Test public void test5() { String str = "http://xxx.xx.com/index.jsp?user=linzhicong&aaa=1"; Pattern pattern = Pattern.compile("user=(.*)&"); Matcher matcher = pattern.matcher(str); while (matcher.find()) { System.out.println(matcher.group(1)); } } console
3.3 实现2java code @Test public void test5() { String str = "http://xxx.xx.com/index.jsp?user=linzhicong&aaa=1" + "http://xxx.xx.com/index.jsp?user=yangfangwei&aaa=1" + "http://xxx.xx.com/index.jsp?login=hahaha&aaa=1"; Pattern pattern = Pattern.compile("user=(.*)&"); Matcher matcher = pattern.matcher(str); while (matcher.find()) { System.out.println(matcher.group(1)); } } console
请思考为什么出现这个结果?怎么修改才能实现需求? 3.4 实现3“user=([^.])&” “user=([w])&” “user=([a-z]*)&” ...... java code @Test public void test5() { String str = "http://xxx.xx.com/index.jsp?user=linzhicong&aaa=1" + "http://xxx.xx.com/index.jsp?user=yangfangwei&aaa=1" + "http://xxx.xx.com/index.jsp?login=hahaha&aaa=1"; Pattern pattern = Pattern.compile("user=([a-z]*)&"); Matcher matcher = pattern.matcher(str); while (matcher.find()) { System.out.println(matcher.group(1)); } } console
4 推荐阅读java正则表达式语法详解及其使用代码实例 返回顶部 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |