.NET正则表达式匹配可以匹配空字符串空字符串、正则表达式、NET

2023-09-05 01:25:58 作者:假装.

我有这样的

模式:

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

目标:

X=113.3413475 Y=18.2054775

和我想匹配的数字。它匹配查找如 http://regexpal.com/ 和正则表达式教练测试软件。

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

但在点网和的http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-ex$p$pssion-tester.ashx

我得到:

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.

感谢和问候, 凯文

推荐答案

是的,这将匹配空字符串。看看它:

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.)

这对我的作品:

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

输出:

113.3413475
18.2054775

有可能是更好的方式做这件事的,无可否认的:)

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