Reputation: 8222
So 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?
Upvotes: 0
Views: 108
Reputation: 82943
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));
Upvotes: 2
Reputation: 8232
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:
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. :)
Upvotes: 5