简体   繁体   English

在C#中按位置替换字符串的一部分

[英]replacing part of a string by position in c#

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 我有一个字符串:===文件内容== \\ r \\ n @这里的东西...} \\ r \\ n \\ r \\ n @这里的东西2 ...} \\ t \\ r \\ n \\ r \\ n \\ r \\ n \\ r \\ n @此处某物3 ...} \\ r @此处某物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. 使用c#,我想获取该字符串中所有以'@'开头并以'}'结尾的字符串,但是由于换行符和制表符不固定,因此在获取'@'和'}'的位置时遇到了问题。 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...}";

See code below: 参见下面的代码:

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

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM