简体   繁体   English

正则表达式不符合C#中的预期

[英]Regex Not Matching as Expected in C#

I'm using the following code: 我正在使用以下代码:

string tile = "a1";
Regex regex= new Regex(@"/([a-z])(\d{1,2})/i");
if (regex.Match(tile).Success) Console.WriteLine("Found a match.");
    else Console.WriteLine("No match.");

and the console returns "No match." 并且控制台返回“ No match”。 The regex itself seems fine to me, but I'm probably missing something simple. 正则表达式本身对我来说似乎不错,但我可能缺少一些简单的东西。 Any help would be appreciated. 任何帮助,将不胜感激。

You're using some javascript regex delineators. 您正在使用一些javascript正则表达式轮廓符。 Try: 尝试:

Regex regex = new Regex(@"([a-z])(\d{1,2})", RegexOptions.IgnoreCase);

Then you'll probably want to use IsMatch() : 然后,您可能要使用IsMatch()

if(regex.IsMatch(tile))
{
    // ...
}

Try this: 尝试这个:

string tile = "a1";
Regex regex = new Regex(@"([a-z])(\d{1,2})", RegexOptions.IgnoreCase);
if (regex.Match(tile).Success) Console.WriteLine("Found a match.");
    else Console.WriteLine("No match.");
Regex regex = new Regex(@"([a-z])(\d{1,2})");

I'm not sure why you have a leading / and a trailing /i . 我不确定为什么您会有前导/后跟/i Those match the characters / and /i , respectively. 它们分别与字符//i匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM