加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:23:41 所属栏目:百科 来源:网络整理
导读:早上查了点儿东西,怕自己忘,就顺便给博客除除草了 import java.util.regex.Matcher;import java.util.regex.Pattern;public class Main {public static void main(String[] args) {//String fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$","")

早上查了点儿东西,怕自己忘,就顺便给博客除除草了

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个相同连续字符

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

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

比如.是6的话,1也就表示6;.表示a的话,1就表示a

{2}表示1重复2遍,所以也可以写成(.)11

明白了之后就很简单了。。。

开始不明白1怎么个意思,后来自己试了一下

^(.)*(.)2{2}.*$和之前的例子意思一样哦,因为括号里多括了个东东,所以如果表示第2个.的话就得用2了

学以致用:

//去除重复的字符
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,"");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读