[英]Replace after a string - Before a character
我有一个像这样的字符串:
string str = "First Option: This is a text. This is second text.";
我可以替换This is a text.
与:
str = str.Replace("This is a text.", "New text");
但是我的不变词是First Option:
并且This is a text
因此如何在First Option:
之后替换文本First Option:
直到出现.
(这意味着在This is second text.
之前This is second text.
)。 在此示例中,预期结果为:
First Option: New text. This is second text.
一种选择是使用Regex.Replace
代替:
str = Regex.Replace(str, @"(?<=First Option:)[^.]*", "New text");
(?<=First Option:)[^.]*
匹配零个或多个除点'.'
以外的字符的序列'.'
,后跟First Option:
通过积极的向后看 。
不是最短的,但是如果要避免使用正则表达式:
string replacement = "New Text";
string s = "First Option: This is a text.This is second text.";
string[] parts = s.Split('.');
parts[0] = "First Option: " + replacement;
s = string.Join(".", parts);
查找.IndexOf()
和Substring(...)
。 那会给你你所需要的:
const string findText = "First Option: ";
var replaceText = "New Text.";
var str = "First Option: This is a text. This is second text.".Replace(findText, "");
var newStr = findText + str.Replace(str.Substring(0, str.IndexOf(".") + 1), replaceText);
Console.WriteLine(newStr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.