replacing part of a string by position in c#

时间:2016-04-04 17:38:09

标签: c# string string-matching

I have a string: ===FILE CONTENT==\r\n@something here... }\r\n\r\n@something here 2... }\t\r\n\r\n\r\n\r\n@something here 3... }\r@something here 4...} \n

using c#, I want get all strings inside this string that starts with '@' and ends with '}', but I having a problem with getting the position of '@' and '}' since newline and tabs are not fix. thank you in advance

here is the sample output:

new string 1 = "@something here... }";
 new string 2 = "@something here 2... }";
 new string 3="@something here 3... }";
 new string 4="@something here 4...}";

2 个答案:

答案 0 :(得分:1)

See code below:

string[] getSubstrings(string str)
{
    return str.Split('@')
        .Select(s => "@" + s.Substring(0, 1 + s.IndexOf('}')))
        .ToArray();
}

答案 1 :(得分:0)

You can use a regex:

var regex = new Regex(@"@[^}]*}");
var listOfMatches = new List<string>();
for (var match = regex.Match(inputString); match.Success; match = match.NextMatch())
{
    listOfMatches.Add(match.Value);
}