正則表達式: 匹配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,}/, "");
相關文章
相關標籤/搜索