C#中的正则表达式IsMatch()方法

Vic*_*lis 3 c# regex

我编译了代码:

namespace TestRegExp
{
    class Program
    {
        static void Main(string[] args)
        {
            if (Regex.IsMatch(args[1], args[0]))
                Console.WriteLine("Input matches regular expression.");
            else
                Console.WriteLine("Input DOES NOT match regular expression.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我跑:

  • TestRegExp.exe ^a\d{5}$ a12345 节目 Input matches regular expression.
  • TestRegExp.exe ^a\d{5}$ aa12345 节目 Input matches regular expression.
  • TestRegExp.exe ^^a\d{5}$ a12345 节目 Input matches regular expression.
  • TestRegExp.exe ^^a\d{5}$ aa12345 节目 Input DOES NOT match regular expression.

为什么第二个选项显示Input matches regular expression.

'^'符号表示字符串init ...好吗?为什么我要重复这个?

Dav*_*ray 8

^在Windows命令行环境中用作转义字符.它告诉命令解释器来对待接下来的文字字符(因为像一些字符<,>以及|具有其他特殊的含义).

^aa在解析时评估.

^^^在解析时评估.


Die*_*hon 7

这与正则表达式本身无关.

如果您打印args[0]到控制台,您将看到它不包含^.这是因为如果未引用表达式,Windows会将其解析为转义字符.

如果你这样称呼它:

TestRegExp.exe "^a\d{5}$" aa12345
Run Code Online (Sandbox Code Playgroud)

你会得到预期的结果.