在字符串后替换 - 在字符之前

时间:2015-12-08 18:37:28

标签: c# replace

我有一个字符串:

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.

3 个答案:

答案 0 :(得分:5)

一种选择是改为使用Regex.Replace

str = Regex.Replace(str, @"(?<=First Option:)[^.]*", "New text");

(?<=First Option:)[^.]*匹配除'.'以外的零个或多个字符的序列,前面有First Option:来自positive look-behind

答案 1 :(得分:1)

不是最短但如果你想避免使用正则表达式:

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

答案 2 :(得分:0)

查找.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);