简体   繁体   English

正则表达式查找同一字符在Java中是否重复3次或更多次

[英]Regular expression find if same character repeats 3 or more no of times in Java

My requirement is to use only Java regular expression to check if a given string contains the same character repeated more than 3 times in continuation within the string. 我的要求是仅使用Java正则表达式来检查给定的字符串是否包含在字符串中连续重复3次以上的相同字符。

For ex : 对于前:

"hello"  -> false
"ohhhhh" -> true
"whatsuppp" -> true

You can use the following regex for your problem: 您可以使用以下正则表达式解决问题:

^.*(.)\1\1.*$

Explanation 说明

  1. ^ starting point of your string ^字符串的起点
  2. .* any char 0 to N times .*任何字符0到N次
  3. (.) one char in the capturing group that will be used by the backreference (.)捕获组中的一个字符,供反向引用使用
  4. \\1 back reference to the captured character (we call it twice to force your 3 times repetition constraint) \\1返回引用捕获的字符(我们两次调用它来强制执行3次重复约束)
  5. .* any char 0 to N times .*任何字符0到N次
  6. $ end of the input string $输入字符串的结尾

I have tested on : 我已经测试过:

hello -> false
ohhhhh -> true
whatsuppp -> true
aaa -> true
aaahhhahj -> true
abcdef -> false
abceeedef -> true

Last but not least, you have to add a backslash \\ before each backslash \\ in your regex before being able to use it in your Java code. 最后但并非最不重要的,你必须添加一个反斜杠\\前每个反斜杠\\能够在Java代码中使用它之前,你的正则表达式。

This give you the following prototype Java code: 这为您提供了以下原型Java代码:

  ArrayList <String> strVector = new ArrayList<String>();
  strVector.add("hello");
  strVector.add("ohhhhh");
  strVector.add("whatsuppp");
  strVector.add("aaa");
  strVector.add("aaahhhahj");
  strVector.add("abcdef");
  strVector.add("abceeedef");

  Pattern pattern = Pattern.compile("^.*(.)\\1\\1.*$");
  Matcher matcher;        

  for(String elem:strVector)
  {
    System.out.println(elem);
    matcher = pattern.matcher(elem);
    if (matcher.find())System.out.println("Found you!");
    else System.out.println("Not Found!");
  }

giving at execution the following output: 在执行时给出以下输出:

hello
Not Found!
ohhhhh
Found you!
whatsuppp
Found you!
aaa
Found you!
aaahhhahj
Found you!
abcdef
Not Found!
abceeedef
Found you!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM