Java-正则使用

Java-正则使用

注意

在Java中由于string的设计,导致斜杠是特殊的字符,所以如若想要在正则中使用斜杠,则需要两个斜杠来表示

eg: \d 需要写成: \\d ,两外 \\\\ 表示匹配单个斜杠

需要用到的两个类:

  • java.util.regex.Pattern 模式类:用来表示一个编译过的正则表达式
  • java.util.regex.Matcher 匹配类:用模式匹配一个字符串所得到的结果

1.判断字符串是否满足正则的两种方式

//判断字符串是否满足正则的两种方式
boolean b1= Pattern.matches("正则表达式","字符串"); //判断是否匹配(整个字符串)
boolean b2= "需要判断的字符串".matches("正则表达式");

2.替换:

	String regular="dog"; //正则
    String str="This is dog1 dog2  dog3";
                
    Pattern pattern = Pattern.compile(regular);
    Matcher matcher=pattern.matcher(str);
    str= matcher.replaceAll("cat"); // 替换所有
    str= matcher.replaceFirst("cat"); //替换第一个

3.获取匹配结果

Pattern pattern = Pattern.compile("正则表达式");
Matcher matcher=pattern.matcher("需要判断的字符串");
while (matcher.find()){   //尝试查找与该模式匹配的输入序列的下一个子序列
    String string = matcher.group(1); //获取每个匹配结果分组为1的值
}

4.Matcher 方法

start()返回匹配到的子字符串在字符串中的索引位置.

end()返回匹配到的子字符串的最后一个字符在字符串中的索引位置.

group()返回匹配到的子字符串

matches() 方法用于在文本中匹配正则表达式(匹配整个文本),不能用于查找正则表达式多次出现

posted @ 2017-08-24 10:33  -Tiger  阅读(357)  评论(0编辑  收藏  举报