创建正则表达式
//要处理的字符串
String content='htsbhdfgsfhsgjs ';
//构造正则表达式
pattern pattern=pattern.com pile (' h.*? s ';
//使用正则表达式匹配字符串
matcher matcher=pattern.matcher (content );
//在字符串中匹配下一个符合公式字符串,不是贪婪模式
matcher.find (;
//整个字符串与正则表达式匹配
matcher.matches (;
//从字符串的第一个字符开始匹配
matcher.lookingAt (;
find、matches、lookingAt三种方法的区别
查找方法
wile(Matcher.find ) () ) ) ) )。
system.out.println (matcher.start ((-' matcher.group ) )- ' matcher.end ) );
}
0 - hts - 3
4 - hdfgs - 9
10 - hs - 12
匹配方法
if(Matcher.Matches () ) ) )。
system.out.println (matcher.start ((-' matcher.group ) )- ' matcher.end ) );
}
0 - htsbhdfgsfhsgjs - 15
锁定方法
if(Matcher.lookingat () ) )
system.out.println (matcher.start ((-' matcher.group ) )- ' matcher.end ) );
}
0 - hts - 3
一致组
//pattern pattern=pattern.com pile (() ) () ) ) ) h.*? s () h.*? s ();
//正则表达式(h.*? s () h.*? s )整体不一致
pattern pattern=pattern.com pile (' (h.*? s () ).*? (h.*? s ();
wile(Matcher.find ) () ) ) ) )。
system.out.println (matcher.start (0)- ' matcher.group(0)0)- ' matcher.end(0)0);
system.out.println (matcher.start (1)- ' matcher.group(1)1)- ' matcher.end(1)1);
system.out.println (matcher.start (2) )- ' matcher.group(2)- ' matcher.end(2) );
system.out.println (matcher.start (3) (- ' matcher.group(3) )- ' matcher.end(3) );
}
0 - htsbhdfgs - 9
0 - hts - 3
3 - b - 4
4 - hdfgs - 9
group取得的是(h . s ) )? (h.*? s )一致以上内容
group(1)获取第一个括号中的内容
group(2)获取第二个括号内的内容
start ) )获取匹配字符串的开头下标
end ) )获取匹配字符串末尾的字符地址
start(index )和end )是第几组的
这里要理解正则表达式,从整体来看,一致的是(h . s ) )? (h.*? s )这种格式的字符串可以用下标获得匹配字符串中用括号括起来的部分
替换
publicstaticvoidmain (string [ ] args ) {
String content='this is T100T,that is T200T ';
String pattern='T.*? t ';
patternr=pattern.com pile (pattern );
matcher matcher=r.matcher (content );
字符串替换第一次=matcher .替换第一次(' TT ' );
stringreplaceallresult=matcher.replace all (' TT );
system.out.println (replace first;
system.out.println (replace all result;
}
执行结果:
this is TT,that is T200T
this is TT,that is TT
一般匹配规则
字符串='hello,heihei,im here '
转义字符,在java正则表达式中,、、只能表示、、匹配项、\"
^一致输入字符串的开始位置^he一致,^llo不一致
$匹配输入字符串末尾位置here$匹配,im$不匹配
一次或多次(hei )指示符合hei、heihi、heihi格式,hei指示符合hei、heiii格式,默认符合贪婪
.r和n以外的任意字符匹配
* 0次或多次
? 表示不贪婪的模式
{3}多沙次,对准h{3}hhh
{ 3,5 }匹配3-5次,h { 3,5 }匹配hhh、hhhh、hhhh均一致
d匹配数字[0-9]等效
s匹配任何空白字符
S匹配非空白字符
n换行符
r回车
f分页符
t选项卡
[abc]匹配a或b或c之一
[a-z] 'a '到' z '的所有小写字母。
不在[^a-z] '到' z '范围内的小写字母。
w与任何字符类匹配的[a-zA-Z0-9]等效
. *?