正则表达式仅用于数字

本文翻译自:Regex for numbers only

I haven't used regular expressions at all, so I'm having difficulty troubleshooting. 我根本没有使用过正则表达式,因此我很难进行故障排除。 I want the regex to match only when the contained string is all numbers; 我希望正则表达式仅在包含的字符串为全数字时才匹配; but with the two examples below it is matching a string that contains all numbers plus an equals sign like "1234=4321". 但是在下面的两个示例中,它匹配包含所有数字和等号(例如“ 1234 = 4321”)的字符串。 I'm sure there's a way to change this behavior, but as I said, I've never really done much with regular expressions. 我敢肯定有一种方法可以改变这种行为,但是正如我所说,我从未真正对正则表达式做过很多事情。

string compare = "1234=4321";
Regex regex = new Regex(@"[\d]");

if (regex.IsMatch(compare))
{ 
    //true
}

regex = new Regex("[0-9]");

if (regex.IsMatch(compare))
{ 
    //true
}

In case it matters, I'm using C# and .NET2.0. 万一重要,我使用的是C#和.NET2.0。


#1楼

参考:https://stackoom.com/question/193v/正则表达式仅用于数字


#2楼

Another way: If you like to match international numbers such as Persian or Arabic, so you can use following expression: 另一种方式:如果您想匹配波斯或阿拉伯等国际号码,则可以使用以下表达式:

Regex = new Regex(@"^[\p{N}]+$");

To match literal period character use: 要匹配文字字符,请使用:

Regex = new Regex(@"^[\p{N}\.]+$");

#3楼

Perhaps my method will help you. 也许我的方法会对您有所帮助。

    public static bool IsNumber(string s)
    {
        return s.All(char.IsDigit);
    }

#4楼

This works with integers and decimal numbers. 这适用于整数和十进制数。 It doesn't match if the number has the coma thousand separator , 如果数字带有逗号分隔符,则不匹配,

"^-?\\d*(\\.\\d+)?$"

some strings that matches with this: 与此匹配的一些字符串:

894
923.21
76876876
.32
-894
-923.21
-76876876
-.32

some strings that doesn't: 一些没有的字符串:

hello
9bye
hello9bye
888,323
5,434.3
-8,336.09
87078.

#5楼

Sorry for ugly formatting. 抱歉,格式不正确。 For any number of digits: 对于任何数字:

[0-9]*

For one or more digit: 对于一位或多位数字:

[0-9]+

#6楼

If you need to check if all the digits are number (0-9) or not, 如果您需要检查所有数字是否都是数字(0-9),

^[0-9]+$

1425 TRUE 1425是

0142 TRUE 0142是

0 TRUE 0是

1 TRUE 1是

154a25 FALSE 154a25错误

1234=3254 FALSE 1234 = 3254假

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值