简体   繁体   中英

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. 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 . (it means before 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:

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

(?<=First Option:)[^.]* matches a sequence of zero or more characters other than dot '.' , preceded by First Option: via a positive look-behind .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM