简体   繁体   中英

Find & Replace Custom Values In a String C#

I am a student developing an application which takes the contents of a PHP file and stores them to a variable.

The user will input what characters/values need to be replaced in the loaded content.

For example :

FIND           REPLACE
echo           Print
<?php          <?
CURL           (space)

These patterns then can be saved to a text file for further use. When the user wants to remove the content according to the pattern, they can do so by clicking a button.

So my question is :

Can this be easily archived via a basic string replace method, or should I go for a more complex regex?

And if I should use regex, how can I create custom regex patterns based on user input?

I'll be very grateful if you can help me with this, thank you.

If you are simply trying to replace a set of characters in a given string with another set of characters, then the string.Replace() method will suit you just fine.

The goal of any programmer should be to write the simplest possible code for a given task. While regexes are well suited to contextual replacements, if all you need is basic find and replace functionality then they are definitely overkill and will only serve to introduce unnecessary complexity into your program.

This can be achieved using simply Replace , a Regex to handle such elaborate requirements would not only be messy, but incredibly difficult to maintain/update with additional items.

How about storing your Find and replace patterns in a Dictionary and then looping through and doing the replace? That way, if you add more items, you just need to add them to your Dictionary . Something like:

Dictionary<string, string> replacements = new Dictionary<string, string>
                                          {
                                              { "echo", "PRINT" },
                                              { "<?php", "<?" },
                                              { "CURL", "(space)" }
                                          }

string yourString; //this is your starter string, populate it with whatever

foreach (var item in replacements)
{
    yourString = yourString.Replace(item.Key, item.Value);
}

None of the answers I've seen so far make mention of being cautious to make sure that an iterative approach doesn't match FIND values that were not there in the original source (eg your first loop might replace echo with Print , but then loop two might replace int (from within the new Print , with eg Int32 leaving PrInt32 ).

You might be "safer" to use a very simple regex just to ensure you're only ever replacing a whole word, which would at least protect you from my above example.

Eg instead of searching for the user-specified string int , wrap that in regex word boundaries and search for that instead \\bint\\b (of course would require careful testing to ensure this works with whatever operators might be in the target file, or that it's appropriate for the given types of search strings etc). You could then provide this as an option (similar to most text-editing software providing a "match whole word only" option).

Also you need to ensure you don't ever iterate over the same search target with the same replace - eg ensure that <? doesn't become <?php and then later become <?<?php etc. Although I don't think any of the answers given here would suffer that problem.

You can use a dictionary to make repeated calls to Replace more easily:

var replacements = new Dictionary<string, string>();
replacements.Add("echo", "print");
replacements.Add("<?php", "<?");
...

foreach(var pair in replacements)
{
    myString = myString.Replace(pair.Key, pair.Value);
}

Or use Linq's Aggregate method.

myString = replacements.Aggregate(myString, (s, p) => s.Replace(p.Key, p.Value));

This will work for simple strings, but the same general design can be used for regex patterns as well:

var replacements = new Dictionary<string, string>();
...

foreach(var pair in replacement)
{
    myString = new RegEx(pair.Key).Replace(myString, pair.Value);
}

And again with Linq:

myString = replacements.Aggregate(myString, (s, p) => new RegEx(pair.Key).Replace(s, p.Value));

Just using String.Replace repeatedly is the easiest way go, but it won't be the fastest. I'd almost try it that way first and then only if it's not fast enough switch to using regular expressions. You'll have to be careful of the possibility that a replacement text might match one of your search fragments, though.

To use regexes, you'd need to Regex.Escape each search string and then concatenate all the escaped patterns using '|' as a separator. Then you can do a single Regex.Replace using a MatchEvaluator to look up the replacements.

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