简体   繁体   中英

Weird Regular Expression (Regex) Matching! Not matching digits

Ok, this is really really weird. I have the following simple regex search pattern

\d*

Unfortunately it doesn't match "7" in

*-7d

But when I tested the following regex search pattern

xx

It matchers "xx" in

asdxxasd

Totally wierd! BTW, i'm using the normal c# regex object. Thanks in advance for any help though!

Sorry, my code is as follows:

public static string FindFirstRegex(string input,string pattern)
{
    try
    {
        Regex _regex = new Regex(@pattern);
        Match match = _regex.Match(input.ToLower());
        if (match.Success)
        {
            return match.Groups[0].Value;
        }
        else
        {
            return null;
        }
    }
    catch
    {
        return "";
    }
}

I call the functions as follows:

MessageBox.Show(utilities.FindFirstRegex("asdxxasd", "xx"));
MessageBox.Show(utilities.FindFirstRegex("ss327d", "\\d*"));

Your regexp is matching 0 or more digits. It begins looking at your pattern, and since the first character is a non-digit, it therefore matches zero digits.

If you used + rather than *, you would force it to start at a digit and then (greedily) get the remainder of the digits.

That is because you use * quantifier, so \\d* means digit, any number of repetitions. In .NET implementation this regex for input *-7d will return 5 matches: empty string , empty string , 7 , empty string and empty string . Use + quantifier instead of * , ie: \\d+ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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