public static final String POEM=
"Twas brilling, and the slithy toves\n" +
"Did gyre and gimble in the wabe.\n"+
"All mimsy were the borogoves,\n" +
"And the mome rathsoutgrable.\n\n"+
"Beware the Jabberwork, my son,\n"+
"The jaws that bite, the claws that catch.\n"+
"Beware hte Jubjub bird, and shun\n"+
"The frumious Bandersnatch.";
public static void main(String[] args) {
// TODO Auto-generated method stub
Matcher m= Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$")
.matcher(POEM);
while (m.find()) {
for (int j = 0; j <= m.groupCount(); j++) {
System.out.print("["+ m.group(j)+ "]");
}
System.out.println();
}
}

output:
[the slithy toves][the][slithy toves][slithy][toves]
[in the wabe.][in][the wabe.][the][wabe.]
[were the borogoves,][were][the borogoves,][the][borogoves,]
[the mome rathsoutgrable.][the][mome rathsoutgrable.][mome][rathsoutgrable.]
[Jabberwork, my son,][Jabberwork,][my son,][my][son,]
[claws that catch.][claws][that catch.][that][catch.]
[bird, and shun][bird,][and shun][and][shun]
[The frumious Bandersnatch.][The][frumious Bandersnatch.][frumious][Bandersnatch.]

解析:

m.groupCout():匹配器匹配的组的总数,不包括0组。

m.group(j):匹配的第j组的值。group(0)是整个表达式

(?m):多行模式

\S:非空白字符

\s:空白字符 ==[ \t\n\x0B\f\r]

2.Matcher.find() vs .lookingAt() vs .matchers()

package com.westward;

import java.util.regex.Matcher;
import java.util.regex.Pattern; public class Demo31 {
public static String input=
"As long as there is injustice, whenever a\n"+
"Targathian baby cries out.wherever a distress\n" +
"signal sounds among the stars ... We'll be there.\n"+
"This fine ship, and this fine crew ...\n" +
"Never give up! Never surrender!"; private static class Display{
private boolean regexPrinted= false;
private String regex;
Display(String regex) {
this.regex= regex;
}
void display(String message){
if (!regexPrinted) {
System.out.println(regex);
regexPrinted = true;
}
System.out.println(message);
}
}
static void examine(String s,String regex){
Display d= new Display(regex);
Pattern p= Pattern.compile(regex);
Matcher m= p.matcher(s);
while (m.find()) {
d.display("find() '"+ m.group() +
"' start= "+m.start()+ " end= "+ m.end());
}
if (m.lookingAt()) {
d.display("lookingAt() '"+ m.group() +
"' start= "+m.start()+ " end= "+ m.end());
}
if (m.matches()) {
d.display("matches() '"+ m.group() +
"' start= "+m.start()+ " end= "+ m.end());
}
}
public static void main(String[] args) {
for (String in : input.split("\n")) {
System.out.println("input :"+ in);
for (String regex : new String[]{"\\w*ere\\w*",
"\\w*ever","T\\w+","Never.*?!"}) {
examine(in, regex);
}
}
}
}

output:
input :As long as there is injustice, whenever a
\w*ere\w*
find() 'there' start= 11 end= 16
\w*ever
find() 'whenever' start= 31 end= 39
input :Targathian baby cries out.wherever a distress
\w*ere\w*
find() 'wherever' start= 26 end= 34
\w*ever
find() 'wherever' start= 26 end= 34
T\w+
find() 'Targathian' start= 0 end= 10
lookingAt() 'Targathian' start= 0 end= 10
input :signal sounds among the stars ... We'll be there.
\w*ere\w*
find() 'there' start= 43 end= 48
input :This fine ship, and this fine crew ...
T\w+
find() 'This' start= 0 end= 4
lookingAt() 'This' start= 0 end= 4
input :Never give up! Never surrender!
\w*ever
find() 'Never' start= 0 end= 5
find() 'Never' start= 15 end= 20
lookingAt() 'Never' start= 0 end= 5
Never.*?!
find() 'Never give up!' start= 0 end= 14
find() 'Never surrender!' start= 15 end= 31
lookingAt() 'Never give up!' start= 0 end= 14
matches() 'Never give up! Never surrender!' start= 0 end= 31

总结:

Matcher.find():匹配字符串的任意位置

Matcher.lookingAt():匹配字符串的开始位置

Matcher.matchers():匹配整个字符串,String.matchers()底层就是调用的它。

3.Pattern标记 (Pattern的几个成员变量)

public static void main(String[] args) {
// TODO Auto-generated method stub
Pattern p= Pattern.compile("^java", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
Matcher m= p.matcher(
"java has regex\nJava has regex\n"+
"JAVA has pretty good regular expressions\n"+
"Regular expressions are in Java");
while (m.find()) {
System.out.println(m.group(0));
// System.out.println(m.group());//the same
}
}

output:
java
Java
JAVA

总结:不同的Pattern标记可以用 或| 来连接。

Pattern.CASE_INSENSITIVE(?i):字母大小写不敏感

Pattern.MULTILINE(?m):多行模式

Thinking in java之正则表达式小例子的更多相关文章

  1. java即时通信小例子

    学习java一段时间了,今天写来一个即时通信的小例子练手在其过程中也学到了一些知识拿出来和大家分享,请路过的各位大神多多赐教... 好了下面讲一下基本的思路: 首先,编写服务器端的程序,简单点说吧就是 ...

  2. Java处理文件小例子--获取全国所有城市的坐标

    需求:前端展示数据,全国城市的坐标

  3. Java枚举的小例子

    有一次工作中,要根据多个参数确定一个值(车辆事件),确定一个值需要的参数大部分的属性名称是相同的,少部分是独有的,但是参数的值几乎都是不同的: 因为参数太多,if-else写起来就太不优雅了,可以参考 ...

  4. Java反射机制小例子

    package com.wjy.main; import java.io.Console; import java.lang.reflect.Constructor; import java.lang ...

  5. 验证java引用的小例子

    1. 声明一个变量person指向一个引用对象, 然后将这个person添加到集合list中, 然后将变量person指向null, 问:list中添加的person变成null了吗? import ...

  6. Web服务器-正则表达式-小例子(3.1.2)

    @ 目录 1.邮箱 2.手机号码 关于作者 1.邮箱 import re def main(): email = input("请输入一个邮件地址:") ret = re.matc ...

  7. Java正则表达式匹配例子

    Java正则表达式匹配例子 package com.ibm.test; import java.util.regex.Matcher; import java.util.regex.Pattern; ...

  8. java连接mysql的一个小例子

    想要用java 连接数据库,需要在classpath中加上jdbc的jar包路径 在eclipse中,Project的properties里面的java build path里面添加引用 连接成功的一 ...

  9. java操作xml的一个小例子

    最近两天公司事比较多,这两天自己主要跟xml打交道,今天更一下用java操作xml的一个小例子. 原来自己操作xml一直用这个包:xstream-1.4.2.jar.然后用注解的方式,很方便,自己只要 ...

随机推荐

  1. Generator 函数的含义与用法

    Generator 函数是协程在 ES6 的实现,最大特点就是可以交出函数的执行权(即暂停执行). function* gen(x){ var y = yield x + 2; return y; } ...

  2. postgresql如何实现group_concat功能

    MySQL有个聚集函数group_concat, 它可以按group的id,将字段串联起来,如 表:id name---------------1 A2 B1 B SELECT id, group_c ...

  3. Linux之free命令

    from http://www.cnblogs.com/peida/archive/2012/12/25/2831814.html free命令可以显示Linux系统中空闲的.已用的物理内存及swap ...

  4. Jquery的普通事件和on的委托事件小案例

    以click的事件为例: 普通的绑定事件:$('.btn').click(function(){})绑定 on绑定事件:$(document).on('click','.btn2',function( ...

  5. QBC用法

    方法 说明 Restrictions.eq = Restrictions.allEq 利用Map来进行多个等于的限制 Restrictions.gt > Restrictions.ge > ...

  6. maven寻找jar

    http://mvnrepository.com/artifact/org.springframework/spring-context

  7. sql中out与output

    --SQLQuery Create By Faywool         create proc Proc_OutPutTest--创建 @numA int,--numA为存储过程的参数 @numB  ...

  8. libsvm-3.21使用文档

    Libsvm is a simple, easy-to-use, and efficient software for SVM classification and regression. (可用于分 ...

  9. Peer Code Reviews Made Easy with Eclipse Plug-In

    欢迎关注我的社交账号: 博客园地址: http://www.cnblogs.com/jiangxinnju/p/4781259.html GitHub地址: https://github.com/ji ...

  10. C/C++中的abort、atexit、exit和_Exit

    这几个函数都在头文件#include <stdlib.h>中声明.exit._Exit与abort函数使程序终止,控制并不返回到这些函数的调用者. exit()函数 void exit(i ...