Hutool使用指南(四):正则工具

     今天介绍Hutool的正则工具,由于和正则表达式关系密切,所以今天只是了解一下正则工具的基本使用,以后会专门介绍正则表达式,到时再结合Hutool详细介绍。

      正则表达式工具类是ReUtil,其中的方法都是static方法。

判断是否匹配

使用 isMatch(String regex,CharSequence content):boolean 方法,第一个参数是正则,第二个是匹配的内容。

看一个小例子:

public class Test{	
    public static void test01() {
	//匹配qq邮箱格式
	String content1="[email protected]";
	String content2="[email protected]";
	String content3="[email protected]";
	String content4="[email protected]";
	String reg="[0-9]{10}@qq.com$";
	boolean matched1=ReUtil.isMatch(reg, content1);
	boolean matched2=ReUtil.isMatch(reg, content2);
	boolean matched3=ReUtil.isMatch(reg, content3);
	boolean matched4=ReUtil.isMatch(reg, content4);
	System.out.println(matched1); 	//true
	System.out.println(matched2);	//false
	System.out.println(matched3);	//false
	System.out.println(matched4);	//false
    }
}

删除所匹配的内容

delFirst(String regex,CharSequence content):String

删除匹配的第一个字符串,返回删除后的字符串

delAll(String regex,CharSequence content):String

删除匹配的所有字符串,返回删除后的字符串

public class Test{
  public static void test02() {
	String content="smartPig,hello;my name is smartpig,smartPig";
	String result=ReUtil.delFirst("smart", content);
	System.out.println("删除第一个smart:");
	System.out.println(result);
	result=ReUtil.delAll("smart", content);
	System.out.println("删除所有smart:");
	System.out.println(result);
	/*结果:
	 删除第一个smart:
	Pig,hello;my name is smartpig,smartPig
	删除所有smart:
	Pig,hello;my name is pig,Pig
	*/
    }

    public static void main(String[] args) {
	Test.test02();
    }

}

得到匹配的内容

使用findAll(String regex, CharSequence content, int group): List<String>方法可以获得所有匹配的内容

public class Test {
	
    /**
     * 	得到所有的匹配内容
     */
    public static void test03() {
	String content="abjgjaaagjgaaaagj";
	//匹配所有a出现了1-4次的字符串
	List<String> results=ReUtil.findAll("a{1,4}", content, 0);
	for(String s:results) {
		System.out.println(s);
	}
	/*结果:
	a
	aaa
	aaaa
	*/
    }
		
    public static void main(String[] args) {
	Test.test03();
    }
}

替换匹配内容

使用replaceAll(CharSequence content, String regex, String replacementTemplate):String方法可以替换匹配的内容。

public class Test{
    /**
    * 	替换匹配内容
    */
    public static void test04() {
	String content="hello1world2thank5you7";
	//将所有数字替换为下划线
	String result=ReUtil.replaceAll(content, "[0-9]", "_");
	System.out.println(result);
	/*结果:
	hello_world_thank_you_
	*/
    }
	
	
    public static void main(String[] args) {
	Test.test04();
    }
}

自动转义特殊字符

使用escape(CharSequence arg0):String方法可以将用于正则表达式中的某些特殊字符进行转义,变成转义字符。

pubic class Test{
    /**
     * 	自动转义特殊字符
     */
    public static void test05() {
	String content="hello$smart[";
	String result=ReUtil.escape(content);
	System.out.println(result);
	/*结果:
	hello\$smart\[
	*/
    }
	
    public static void main(String[] args) {
	Test.test05();
    }
}

猜你喜欢

转载自blog.csdn.net/tianc_pig/article/details/88134882