简体   繁体   English

正则表达式仅允许使用0-9和-字符以及点(。)

[英]Regex allow only 0-9 and the - character, and dot (.)

I Need a regex to validate 0-9 and allow . 我需要一个正则表达式来验证0-9并允许. and - characters. -字符。

Following is working for 0-9 and . 以下适用于0-9. characters: 字符:

Regex invalidCharsRegex = new Regex(@"^*[0-9\.]+$");

Your regex is weird... 您的正则表达式很奇怪...

Regex invalidCharsRegex = new Regex(@"^*[0-9\.]+$");

Remove the first asterisk, it's not doing anything good. 删除第一个星号,这没有任何好处。

And to allow - characters, you simply add it to the character class. 并允许-字符,你可以将它添加到字符类。 Also, you don't need to escape the dot in a character class: 另外,您无需在字符类中转义点:

Regex invalidCharsRegex = new Regex(@"^[0-9.-]+$");

If you're trying to validate a number, this regex will have to be revised, because the regex will accept ---- or ..... . 如果您要验证数字,则必须修改此正则表达式,因为该正则表达式将接受----..... Something a bit like this for integer/floating numbers: 整数/浮点数有点像这样:

Regex invalidCharsRegex = new Regex(@"^\-?[0-9]+(?:\.[0-9]+)?$");
Regex invalidCharsRegex = new Regex(@"(?<=^| )\d+(\.\d+)?(?=$| )|(?<=^| )\.\d+(?=$| )");

这将允许使用数字1、1.2,.1等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM