[英]Replace after a string - Before a character
I have a string like : 我有一个像这样的字符串:
string str = "First Option: This is a text. This is second text.";
I can replace This is a text.
我可以替换
This is a text.
with : 与:
str = str.Replace("This is a text.", "New text");
But my constant word is First Option:
and This is a text
is not constant so how can replace the text after First Option:
until occurring .
但是我的不变词是
First Option:
并且This is a text
因此如何在First Option:
之后替换文本First Option:
直到出现.
(it means before This is second text.
). (这意味着在
This is second text.
之前This is second text.
)。 In this example the expecting result is : 在此示例中,预期结果为:
First Option: New text. This is second text.
One option is to use Regex.Replace
instead: 一种选择是使用
Regex.Replace
代替:
str = Regex.Replace(str, @"(?<=First Option:)[^.]*", "New text");
(?<=First Option:)[^.]*
matches a sequence of zero or more characters other than dot '.'
(?<=First Option:)[^.]*
匹配零个或多个除点'.'
以外的字符的序列'.'
, preceded by First Option:
via a positive look-behind . ,后跟
First Option:
通过积极的向后看 。
Not the shortest but if you want to avoid regular expressions: 不是最短的,但是如果要避免使用正则表达式:
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);
Look up .IndexOf()
and Substring(...)
. 查找
.IndexOf()
和Substring(...)
。 That will give you what you need: 那会给你你所需要的:
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.