.NET Regex whole string matching [duplicate]

社会主义新天地 提交于 2019-12-10 17:58:02

问题


If we take the following patterns: 70000@.* and 970000@.* the string 970000@ILoveFishSticksAndTarTarSauce.com:5060 is returning a match to 70000@.*

I understand why it matches, but I need to modify the regex to only do a full string match.

Any ideas?

Thanks!

I am using the .Net 3.5 library

Here is the code:

[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;
            }
        }

    }

回答1:


Try using the

^$ 

operators in your regex to force beginning and end matching.




回答2:


Start the pattern with ^ and end with $. These match the start of the line or string and end of the line or string respectively.

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


来源:https://stackoverflow.com/questions/15261613/net-regex-whole-string-matching

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!