Java 正则表达式详细使用
Java正则表达式的使用,具体内容如下所示:
java.util.regex.Pattern java.util.regex.Matcher
1.Match
match是从字符串最头部开始匹配,一直到结束,需要匹配整个串
Stringcontent="Welcome,bob!";
content.match("bob");//false
content.match(".*bob")//false
content.match(".*bob.*")//true
Stringstr="test@yahoo.com.cn";
Patternpattern=Pattern.compile("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+",Pattern.CASE_INSENSITIVE);
Matchermatcher=pattern.matcher(str);
booleana=matcher.matches();//匹配的时候返回true
2.Find
booleanb=matcher.find();//包含正则匹配的串为true
//找到所有匹配的串
while(matcher.find()){
Stringextracted=matcher.group(0)
}
3.Replace
matcher.replaceFirst("")
matcher.replaceAll("");
4.Group
group(0)代表整个表达式
Stringline="#星座运势#20171013";
Stringpattern="\\#(\\p{L}*)\\#(\\d+)";//\p{L}匹配unicodeanykindofletterfromanylanguage
//创建Pattern对象
Patternr=Pattern.compile(pattern);
//现在创建matcher对象
Matcherm=r.matcher(line);
if(m.find()){
System.out.println("Foundvalue:"+m.group(0));//"#星座运势#20171013"
System.out.println("Foundvalue:"+m.group(1));//星座运势
System.out.println("Foundvalue:"+m.group(2));//20171013
}else{
System.out.println("NOMATCH");
}
总结
以上所述是小编给大家介绍的Java正则表达式详细使用,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!