用正则表达式匹配数字——只有数字和逗号 [英] Matching numbers with regular expressions — only digits and commas

查看:75
本文介绍了用正则表达式匹配数字——只有数字和逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何为示例值构建正则表达式:

I can't figure out how to construct a regex for the example values:

123,456,789
-12,34
1234
-8

你能帮我吗?

推荐答案

如果您只想允许数字和逗号,^[-,0-9]+$ 是您的正则表达式.如果您还想允许空格,请使用 ^[-,0-9 ]+$.

If you only want to allow digits and commas, ^[-,0-9]+$ is your regex. If you also want to allow spaces, use ^[-,0-9 ]+$.

但是,如果您想允许正确的数字,最好使用这样的方法:

However, if you want to allow proper numbers, better go with something like this:

^([-+] ?)?[0-9]+(,[0-9]+)?$

或简单地使用 .net 的数字解析器(用于各种NumberStyles,请参阅 MSDN):

or simply use .net's number parser (for the various NumberStyles, see MSDN):

try {
    double.Parse(yourString, NumberStyle.Number);
}
catch(FormatException ex) {
    /* Number is not in an accepted format */
}

这篇关于用正则表达式匹配数字——只有数字和逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆