Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET REGEX Matching matches empty strings

I have this

pattern:

[0-9]*\.?[0-9]*

Target:

X=113.3413475 Y=18.2054775

And i want to match the numbers. It matches find in testing software like http://regexpal.com/ and Regex Coach.

But in Dot net and http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx

I get:

Found 11 matches:

1.
2.
3.
4.
5.
6.  113.3413475
7.
8.
9.
10. 18.2054775
11.

String literals for use in programs:

C#
    @"[0-9]*[\.]?[0-9]*"

Any one have any idea why i'm getting all these empty matches.

Thanks and Regards, Kevin

like image 590
Kev84 Avatar asked Dec 07 '22 19:12

Kev84


1 Answers

Yes, that will match empty string. Look at it:

[0-9]* - zero or more digits
\.?    - an optional period
[0-9]* - zero or more digits

Everything's optional, so an empty string matches.

It sounds like you always want there to be digits somewhere, for example:

[0-9]+\.[0-9]*|\.[0-9]+|[0-9]+

(The order here matters, as you want it to take the most possible.)

That works for me:

using System;
using System.Text.RegularExpressions;

class Test
{
    static void Main(string[] args)
    {
        string x = "X=113.3413475 Y=18.2054775";
        Regex regex = new Regex(@"[0-9]+\.[0-9]*|\.[0-9]+|[0-9]+");
        var matches = regex.Matches(x);
        foreach (Match match in matches)
        {
            Console.WriteLine(match);
        }
    }
}

Output:

113.3413475
18.2054775

There may well be better ways of doing it, admittedly :)

like image 66
Jon Skeet Avatar answered Dec 14 '22 14:12

Jon Skeet