views:

976

answers:

5

Hi,

What is the PHP preg_replace in C#?

I have an array of string that I would like to replace by an other array of string. Here is an example in PHP. How can I do something like that in C# without using .Replace("old","new").

$patterns[0] = '/=C0/';
$patterns[1] = '/=E9/';
$patterns[2] = '/=C9/';


$replacements[0] = 'à';
$replacements[1] = 'é';
$replacements[2] = 'é';
return preg_replace($patterns, $replacements, $text);
+1  A: 

You are looking for System.Text.RegularExpressions;

using System.Text.RegularExpressions;

Regex r = new Regex("=C0");
string output = r.Replace(text);

To get PHP's array behaviour the way you have you need multiple instances of `Regex

However, in your example, you'd be much better served by .Replace(old, new), it's much faster than compiling state machines.

Matthew Scharley
+3  A: 

Real men use regular expressions, but here is an extension method that adds it to String if you wanted it:

public static class ExtensionMethods
{
    public static String PregReplace(this String input, string[] pattern, string[] replacements)
    {
        if (replacements.Length != pattern.Length)
            throw new ArgumentException("Replacement and Pattern Arrays must be balanced");

        for (var i = 0; i < pattern.Length; i++)
        {
            input = Regex.Replace(input, pattern[i], replacements[i]);                
        }

        return input;
    }
}

You use it like this:

 class Program
    {
        static void Main(string[] args)
        {
            String[] pattern = new String[4];
            String[] replacement = new String[4];

            pattern[0] = "Quick";
            pattern[1] = "Fox";
            pattern[2] = "Jumped";
            pattern[3] = "Lazy";

            replacement[0] = "Slow";            
            replacement[1] = "Turtle";
            replacement[2] = "Crawled";
            replacement[3] = "Dead";

            String DemoText = "The Quick Brown Fox Jumped Over the Lazy Dog";

            Console.WriteLine(DemoText.PregReplace(pattern, replacement));
        }        
    }
FlySwat
Cute output... How'd you manage to add the function to String though?
Matthew Scharley
Look up Extension Methods.
FlySwat
It's a C# 3.0 feature if I remember correctly.
macbirdie
I really do not see how to change String class.
Daok
See how he's passing 'this' in for the first param of his preg replace method? That does all the magic of extending the String class.
tyshock
+2  A: 

You can use .Select() (in .NET 3.5 and C# 3) to ease applying functions to members of a collection.

stringsList.Select( s => replacementsList.Select( r => s.Replace(s,r) ) );

You don't need regexp support, you just want an easy way to iterate over the arrays.

Vinko Vrsalovic
A: 

Edit: Uhg I just realized this question was for 2.0, but I'll leave it in case you do have access to 3.5.

Just another take on the Linq thing. Now I used List<Char> instead of Char[] but that's just to make it look a little cleaner. There is no IndexOf method on arrays but there is one on List. Why did I need this? Well from what I am guessing, there is no direct correlation between the replacement list and the list of ones to be replaced. Just the index.

So with that in mind, you can do this with Char[] just fine. But when you see the IndexOf method, you have to add in a .ToList() before it.

Like this: someArray.ToList().IndexOf

  String text;
  List<Char> patternsToReplace;
  List<Char> patternsToUse;

  patternsToReplace = new List<Char>();
  patternsToReplace.Add('a');
  patternsToReplace.Add('c');
  patternsToUse = new List<Char>();
  patternsToUse.Add('X');
  patternsToUse.Add('Z');

  text = "This is a thing to replace stuff with";

  var allAsAndCs = text.ToCharArray()
                 .Select
                 (
                   currentItem => patternsToReplace.Contains(currentItem) 
                     ? patternsToUse[patternsToReplace.IndexOf(currentItem)] 
                     : currentItem
                 )
                 .ToArray();

  text = new String(allAsAndCs);

This just converts the text to a character array, selects through each one. If the current character is not in the replacement list, just send back the character as is. If it is in the replacement list, return the character in the same index of the replacement characters list. Last thing is to create a string from the character array.

  using System;
  using System.Collections.Generic;
  using System.Linq;
Programmin Tool
A: 
public static class StringManipulation
{
    public static string PregReplace(string input, string[] pattern, string[] replacements)
    {
        if (replacements.Length != pattern.Length)
            throw new ArgumentException("Replacement and Pattern Arrays must be balanced");

        for (int i = 0; i < pattern.Length; i++)
        {
            input = Regex.Replace(input, pattern[i], replacements[i]);                
        }

        return input;
    }
}

Here is what I will use. Some code of Jonathan Holland but not in C#3.5 but in C#2.0 :)

Thx all.

Daok