0

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?

2 Answers 2

5

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. :)

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for pragmatic approach. I like regex as much as the next guy, but if a simpler approach works I'm all for it.
Indeed. It's also very easy to write seemingly innocuous regexes that perform appallingly (often in cases where it cannot find a match). If I can get what I want with basic string methods like Split, StartsWith, EndsWith or Contains then I usually will.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.