正则表达式: 匹配n个相同连续字符

早上查了点儿东西,怕本身忘,就顺便给博客除除草了java

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Main {

	public static void main(String[] args) {
		//String fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");
		//System.out.println(fileNameWithOutExt);
		//String testString = "ABBCC".replaceFirst("[A|B|C]{2,}", "");
		//System.out.println(testString);
		String pwd ="36667";
		String regx = "^.*(.)\\1{2}.*$";
		Matcher m = null;
		Pattern p = null;
		p = Pattern.compile(regx);
		m = p.matcher(pwd);
		if(m.matches()) {
			System.out.println("It matches the pattern!");
		}
	}

}

上面这段代码就是匹配一个串里是否有3个相同连续字符code

匹配3个连续相同字符的是(.)\1{2}这一小段xml

括号表示组,是配合\1来用的,而后\1表示组里面第一个匹配到的东东,在我这里就表示.表示的那个字符博客

好比.是6的话,\1也就表示6;.表示a的话,\1就表示ait

{2}表示\1重复2遍,因此也能够写成(.)\1\1class

明白了以后就很简单了。。。test

开始不明白\1怎么个意思,后来本身试了一下import

^(.)*(.)\2{2}.*$和以前的例子意思同样哦,由于括号里多括了个东东,因此若是表示第2个.的话就得用\2了file

学以至用:im

//去除重复的字符
assert "ABC" == "ABBCC".replaceAll("(?s)(.)(?=.*\\1)", "");

//去除相同连续字符
assert "A" == "ABBCCC".replaceAll(~/([\D])\1+/, "");

assert "A" == "ABBCC".replaceAll(~/([A|B|C])\1{1,}/, "");

assert "A" == "ABBCCC".replaceAll(~/([A|B|C])\1{1,}/, "");
相关文章
相关标签/搜索