C# Regex Replacing
S开发者_如何学Goo basically, I have a string like this:
Some Text Here | More Text Here | Even More Text Here
And I want to be able to replace the text between the two bars with New Text
, so it would end up like:
Some Text Here | New Text | Even More Text Here
I'm assuming the best way is with regexes... so I tried a bunch of things but couldn't get anything to work... Help?
For a simple case like this, the best apprach is a simple string split:
string input = "foo|bar|baz";
string[] things = input.Split('|');
things[1] = "roflcopter";
string output = string.Join("|", things); // output contains "foo|roflcopter|baz";
This relies on a few things:
- There are always 3 pipe-delimited text strings.
- There is no insignificant spaces between the pipes.
To correct the second, do something like:
for (int i = 0; i < things.Length; ++i)
things[i] = things[i].Trim();
To remove whitespace from the beginning and end of each element.
The general rule with regexes is that they should usually be your last resort; not your first. :)
If you want to use regex...try this:
String testString = "Some Text Here | More Text Here | Even More Text Here";
Console.WriteLine(Regex.Replace(testString,
@"(.*)\|([^|]+)\|(.*)",
"$1| New Text |$3",
RegexOptions.IgnoreCase));
精彩评论