【发布时间】:2015-12-08 18:37:27
【问题描述】:
我有一个类似的字符串:
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: 之后的文本直到出现.(这意味着在This is second text. 之前)。
在这个例子中,预期的结果是:
First Option: New text. This is second text.
【问题讨论】:
-
要么使用
String.IndexOf获取索引并使用字符串长度来计算要替换的字符串的位置,要么查看正则表达式(regex)。 -
改用
Regex.Replace。