Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find & Replace Custom Values In a String C#

Tags:

c#

regex

replace

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.

like image 756
DriverBoy Avatar asked Dec 26 '22 07:12

DriverBoy


2 Answers

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);
}
like image 177
mattytommo Avatar answered Dec 28 '22 21:12

mattytommo


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.

like image 30
Levi Botelho Avatar answered Dec 28 '22 22:12

Levi Botelho