标签:java 查找 替换 lookingat appendreplacement
import java.util.regex.*; public class TestRegularExpression { public static void main(String[] args) { String strCharSequence = "abcabcabcdefabc"; String strRegex = "(abc)+"; Pattern p = Pattern.compile(strRegex); Matcher m = p.matcher(strCharSequence); while(m.find()) { <span style="white-space:pre"> </span>System.out.println("Match \"" + m.group() + "\" at positions " + m.start() + "-" + (m.end() - 1)); } } }输出结果:
Match "abcabcabc" at positions 0-8 Match "abc" at positions 12-14程序说明:这个程序在字符串abcabcabcdefabc通过正则表达式(abc)+进行匹配。并且利用了matcher.find()函数进行查找,现在就只需要知道find()函数能进行多次匹配就好了,matcher.group()方法能返回匹配的整个匹配结果,start()函数返回匹配位置的起始索引,end()方法返回所匹配的最后字符加1的值。下面我们详细地介绍一下有关于查找的几个常用的方法matches,lookingAt和find的区别。
import java.util.regex.Matcher; import java.util.regex.Pattern; public class IOTest { public static void main(String[] args){ Pattern pattern = Pattern.compile("\\d{3,5}"); String charSequence = "123-34345-234-00"; Matcher matcher = pattern.matcher(charSequence); //虽然匹配失败,但由于charSequence里面的"123"和pattern是匹配的,所以下次的匹配从位置4开始 print(matcher.matches()); //测试匹配位置 matcher.find(); print(matcher.start()); //使用reset方法重置匹配位置 matcher.reset(); //第一次find匹配以及匹配的目标和匹配的起始位置 print(matcher.find()); print(matcher.group()+" - "+matcher.start()); //第二次find匹配以及匹配的目标和匹配的起始位置 print(matcher.find()); print(matcher.group()+" - "+matcher.start()); //第一次lookingAt匹配以及匹配的目标和匹配的起始位置 print(matcher.lookingAt()); print(matcher.group()+" - "+matcher.start()); //第二次lookingAt匹配以及匹配的目标和匹配的起始位置 print(matcher.lookingAt()); print(matcher.group()+" - "+matcher.start()); } public static void print(Object o){ System.out.println(o); } }输出结果:
false 4 true 123 - 0 true 34345 - 4 true 123 - 0 true 123 - 0
//: strings/TheReplacements.java import java.util.regex.*; public class TheReplacements { private static final String CONSTSTRING = "fat cat, fat cat, fat cat, I like."; public static void main(String[] args) throws Exception { Pattern p = Pattern.compile("cat"); Matcher m = p.matcher(CONSTSTRING); //replaceFirst()只替换匹配到的第一个地方 System.out.println(m.replaceFirst("dog")); //replaceAll()替换所有匹配到的地方 p = Pattern.compile("cat"); m = p.matcher(CONSTSTRING); System.out.println(m.replaceAll("dog")); //appendReplacement()将替换位置处及之前位置处的字符复制到StringBuffer中; //appendTail()将替换位置之后的字符复制到StringBuffer p = Pattern.compile("cat"); m = p.matcher(CONSTSTRING); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, "dog"); System.out.println(sb.toString()); } m.appendTail(sb); System.out.println(sb.toString()); } }输出结果:
fat dog, fat cat, fat cat, I like. fat dog, fat dog, fat dog, I like. fat dog fat dog, fat dog fat dog, fat dog, fat dog fat dog, fat dog, fat dog, I like.
java中使用Pattern类中和Matcher类进行查找和替换,你会吗?
标签:java 查找 替换 lookingat appendreplacement
原文地址:http://blog.csdn.net/xiaxia__/article/details/41775721