.NET正则表达式全字符串匹配

3
如果我们采用以下模式:70000@.*和970000@.*,则字符串970000@ILoveFishSticksAndTarTarSauce.com:5060将返回与70000@.*的匹配结果。我知道为什么会匹配,但我需要修改正则表达式以仅进行完整字符串匹配。有任何想法吗?谢谢!我正在使用.Net 3.5库。以下是代码:
[Microsoft.SqlServer.Server.SqlProcedure]
    public static void RouteRegex(string phoneNumber, out string value)
    {
        if (string.IsNullOrEmpty(phoneNumber))
        {
            value = string.Empty;
            return;
        }
        const string strCommand =
            "Select RouteID,sequence,Pattern From SIPProxyConfiguration.dbo.Routes order by routeid, sequence asc";
        using (var connection = new SqlConnection("context connection=true"))
        {
            try
            {
                connection.Open();
                using (var command =new SqlCommand(strCommand,connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var regEx = reader[2] as string;
                            if (string.IsNullOrEmpty(regEx)) continue;
                            var routeId = reader[0];
                            var sequence = reader[1];
                            var match = Regex.Match(phoneNumber, regEx);
                            Regex.IsMatch()
                            if (!match.Success) continue;
                            value = routeId.ToString();
                            return;
                        }
                    }

                }
                value = "No Match!";
            }
            catch (Exception ex)
            {
                value = ex.Message;
                return;
            }
        }

    }
2个回答

6

Try using the

^$ 

在您的正则表达式中使用操作符以强制匹配开头和结尾。


非常感谢!我在记事本++中尝试了这个(众所周知正则表达式有限制),但它没有起作用。明天我会将它放到CLR SPROC中并尝试一下。.NET Regex库是否有已知的限制? - Wjdavis5
我不知道有没有其他方法。我经常使用这些运算符。此外,我通常使用http://regexpal.com/来测试它们,它可以与.NET一起使用。 - Matthew Shea

4

^开头并以$结尾的模式,匹配行或字符串的开头和结尾。

"^70000@.*$" matches "70000@fishsticksforlife.com" but not "970000@tatatotartar.com"
"^970000@.*$" matches "970000@tatatotartar.com"

@Wjdavis5 - 你可以在这里测试:http://regex101.com/r/yQ8xY9 - Jay Walker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接