从长字符串Regex

时间:2019-03-15 09:58:48

标签: c# regex

我有这样的字符串

   jasabcasjlabcdjjakabcdehahakabcdef...//any number of characters

我想要返回这些子字符串的正则表达式

  [abc],[abcd],[abcde],[abcdef],....

我已经写了类似这样的正则表达式

 @"abc(?=[d-z])+

但是它没有带来我想要的东西,我已经尝试了一段时间,请帮忙

谢谢

2 个答案:

答案 0 :(得分:1)

采用foreach循环的方法

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

答案 1 :(得分:1)

Linq方法

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