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

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

问题描述

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

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天全站免登陆