Check if a string in it has a sequential repeating substring

I want to accept only strings that do not have a substring repeated three times in a row in them. The substring is not known in advance. For example, "a4a4a4123" contains "a4"; "abcdwwwabcd" is "w"; "abcde" is valid without triple repetitions.

I tried to implement it myself, but this only works under substrings with one letter:

public bool IsValid(string password) { var validate = true; char lastLetter = ' '; var count = 1; for (int pos = 0; pos < password.Length; pos++) { if (password[pos] == lastLetter) { count++; if (count > 2) { validate = false; break; } } else { lastLetter = password[pos]; count = 1; } } return validate; } 
+4
source share
3 answers

Try the following:

 bool result = Regex.IsMatch(input, @".*(.+).*\1.*\1.*"); 

Basically, it checks to see if the pattern of one or more characters 3 or more times on the same line.

Full explanation:

First, it matches 0 or more characters at the beginning of a line. Then it captures a group of one or more. Then it matches 0 or more, and then the group again. Then 0 or more again , and then capture again. Then again 0 or more.

If you want the string to be consistent, try the following:

 bool result = Regex.IsMatch(input, @".*(.+)\1\1.*"); 

In addition, some performance test results:

 Non-consecutive: 312ms Consecutive: 246ms 

Tests were performed using this program:

 using System; using System.Diagnostics; using System.Text.RegularExpressions; class Program { public static void Main(string[] args) { string input = "brbrbr"; Regex one = new Regex(@".*(.+).*\1.*\1.*"); for (int i = 0; i < 5; i++) { bool x = one.IsMatch(input); //warm regex up } Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < 100000; i++) { bool x = one.IsMatch(input); } sw.Stop(); Console.WriteLine("Non-consecutive: {0}ms", sw.ElapsedMilliseconds); Regex two = new Regex(@".*(.+)\1\1.*"); for (int i = 0; i < 5; i++) { bool x = two.IsMatch(input); //warm regex up } Stopwatch sw2 = Stopwatch.StartNew(); for (int i = 0; i < 100000; i++) { bool x = two.IsMatch(input); } sw.Stop(); Console.WriteLine("Consecutive: {0}ms", sw2.ElapsedMilliseconds); Console.ReadKey(true); } } 
+9
source

Regex is how I would attack this:

 static void Main(string[] args) { string text = "C# is the best language there is in the world."; string search = "the"; Match match = Regex.Match(text, search); Console.WriteLine("there was {0} matches for '{1}'", match.Groups.Count, match.Value); Console.ReadLine(); } 

How to find multiple occurrences with regex groups?

0
source
 Regex.Matches( "a4a4a4123", "a4" ).Count >= 3 
-1
source

Source: https://habr.com/ru/post/1483800/


All Articles