user786
user786

Reputation: 4364

get matching substrings from long string Regex

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

Answers (2)

fubo
fubo

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

fubo
fubo

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

Related Questions