Reputation: 4364
I have a string like this
jasabcasjlabcdjjakabcdehahakabcdef...//any number of characters
I want regex that returns these substrings
[abc],[abcd],[abcde],[abcdef],....
I have written regex something like this
@"abc(?=[d-z])+
But it's not bringing what I want, I have been trying for some time, please help
Thanks
Upvotes: 1
Views: 47
Reputation: 45967
Linq approach
string input = "jasabcasjlabcdjjakabcdehahakabcdef";
string[] result = Regex.Split(input, @"(?=abc)")
.Select(x => string.Concat(x.TakeWhile((y, i) => y == ('a' + i))))
.Where(x => !string.IsNullOrEmpty(x))
.ToArray();
https://dotnetfiddle.net/tahJ4U
Upvotes: 1
Reputation: 45967
Approach with a foreach
-loop
string input = "jasabcasjlabcdjjakabcdehahakabcdef";
List<string> result = new List<string>();
string temp = string.Empty;
foreach(char c in input)
{
if(c == 'a' && temp == string.Empty)
{
temp = string.Empty;
temp += c;
}
else if(c - 1 == temp.LastOrDefault())
{
temp += c;
}
else if (!string.IsNullOrEmpty(temp))
{
if (temp.StartsWith("abc"))
{
result.Add(temp);
}
temp = string.Empty;
}
}
if (temp.StartsWith("abc"))
{
result.Add(temp);
}
https://dotnetfiddle.net/I4t9Cq
Upvotes: 1