加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – .NET REGEX匹配匹配空字符串

发布时间:2020-12-16 00:00:21 所属栏目:百科 来源:网络整理
导读:我有这个 图案: [0-9]*.?[0-9]* 目标: X=113.3413475 Y=18.2054775 我想匹配数字.它匹配http://regexpal.com/和Regex Coach等测试软件中的find. 但在Dot net和http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
我有这个

图案:

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

目标:

X=113.3413475 Y=18.2054775

我想匹配数字.它匹配http://regexpal.com/和Regex Coach等测试软件中的find.

但在Dot net和http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-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]*"

任何人都知道为什么我得到所有这些空的比赛.

感谢致敬,
凯文

解决方法

是的,那将匹配空字符串.看它:

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

一切都是可选的,所以空字符串匹配.

听起来你总是希望在某处有数字,例如:

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

(这里的顺序很重要,因为你希望它尽可能地采取.)

这对我行得通:

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

无可否认,可能有更好的方法做到这一点:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读