简体   繁体   中英

C# Regex Replacing

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?

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

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