user1034912
user1034912

Reputation: 2257

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*"));

Upvotes: 1

Views: 474

Answers (2)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

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 *, i.e.: \d+.

Upvotes: 4

Daniel Widdis
Daniel Widdis

Reputation: 9091

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.

Upvotes: 5

Related Questions