我可以在C#中定义类似Perl的绑定运算符(=〜)吗? [英] Can I define a Perl-like binding operator (=~) in C#?
问题描述
我真的很喜欢能够在Perl中使用=〜和!〜根据正则表达式评估字符串.我想将此功能移植到C#,但看来,尽管您可以重载运算符,但不能创建新的运算符.
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.
我正在考虑扩展字符串类型以提供Match()方法,该方法将允许我传递正则表达式以进行评估,但是我想知道还有更好的方法.
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?
推荐答案
尝试为字符串类创建一个扩展方法,该扩展类充当Regex.Match的快捷方式". 像这样:
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);
}
}
这篇关于我可以在C#中定义类似Perl的绑定运算符(=〜)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!