views:

379

answers:

2

I really like being able to use =~ and !~ in Perl to evaluate a string against a regular expression. I'd like to port this functionality over to C#, but it appears that, while you can overload operators, you can't create new ones.

I'm considering extending the string type to provide a Match() method that will allow me to pass a regular expression in to be evaluated, but I'm wondering of there's a better way.

Anyone have a better solution?

A: 

In my experience .NET supports the same features as Perl regular expressions, but the syntax is much more verbose, so it takes a little getting use to.

C# doesn't support the concept of implicit variables, so you always have to supply both the input string and the match pattern. In other words it is the short cut which is missing from .NET not the explicit matching via =~ and !~.

Regex.Match does the same thing as =~ if you just want to find matches. If you want to match and replace, you have to use the Replace method. For the !~ operator, you just have to use ! and the relevant Regex method.

It takes a bit more typing, but you can get the effect you're looking for.

Brian Rasmussen
+1  A: 

Try creating an extension method to the string class that acts a "shortcut" to Regex.Match. Something like this:

public static class RegexExtensions
{
    public static bool Match(this string text, Regex re)
    {
        return Regex.Match(text, re);
    }
}
Martinho Fernandes
Yeah, this is what I had in mind. I would really love to have the ability to create new operators, maybe we'll see that functionality in the next .Net release.
Tequila Jinx