当前位置: 移动技术网 > IT编程>开发语言>Java > Java 正则表达式详细使用

Java 正则表达式详细使用

2019年07月19日  | 移动技术网IT编程  | 我要评论

java 正则表达式的使用,具体内容如下所示:

java.util.regex.pattern
java.util.regex.matcher

1.match

match 是从字符串最头部开始匹配,一直到结束,需要匹配整个串

string content = "welcome, bob!";
content.match("bob");  //false
content.match(".*bob")  //false
content.match(".*bob.*") //true
string str="test@yahoo.com.cn";
pattern pattern = pattern.compile("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+",pattern.case_insensitive);
matcher matcher = pattern.matcher(str);
boolean a = matcher.matches(); //匹配的时候返回true

2.find

boolean b = matcher.find(); //包含正则匹配的串为true
// 找到所有匹配的串
while(matcher.find()) {
  string extracted = matcher.group(0)
}

3.replace

matcher.replacefirst("")
matcher.replaceall("");

4.group

group(0) 代表整个表达式
string line = "#星座运势#20171013";
string pattern = "\\#(\\p{l}*)\\#(\\d+)"; //\p{l} 匹配 unicode any kind of letter from any language
// 创建 pattern 对象
pattern r = pattern.compile(pattern);
// 现在创建 matcher 对象
matcher m = r.matcher(line);
if (m.find( )) {
  system.out.println("found value: " + m.group(0) );  // "#星座运势#20171013"
  system.out.println("found value: " + m.group(1) );  // 星座运势
  system.out.println("found value: " + m.group(2) );  // 20171013
} else {
  system.out.println("no match");
}

总结

以上所述是小编给大家介绍的java 正则表达式详细使用,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网