Can I define a Perl-like binding operator (= ~) in C #?

I really like being able to use = ~ and! ~ in Perl to evaluate string against regex. I would like to convey this functionality in C #, but it seems that although you can overload operators, you cannot create new ones.

I am considering expanding the type of a string to provide a Match () method that will allow me to pass in a regular expression for evaluation, but I wonder where is better.

Does anyone have a better solution?

+1
c # regex perl operator-overloading
Feb 07 '09 at 7:46
source share
2 answers

Try creating an extension method for the string class that runs the shortcut for Regex.Match. Something like that:

public static class RegexExtensions { public static bool Match(this string text, Regex re) { return Regex.Match(text, re); } } 
+1
Feb 07 '09 at 14:06
source share
β€” -

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

C # does not support the concept of implicit variables, so you always need to supply both the input string and the matching pattern. In other words, this abbreviation, missing in .NET, is not an explicit mapping through = ~ and! ~.

Regex.Match does the same as = ~ if you just want to find matches. If you want to combine and replace, you must use the Replace method. For the operator! ~ You just need to use! and the corresponding Regex method.

It takes a little more text input, but you can get the effect you are looking for.

0
Feb 07 '09 at 7:50
source share



All Articles