[英]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.