有人可以帮助我使用正则表达式吗?基本上,我想要一个与十进制数匹配的正则表达式.
Could somebody help me with regex? Basically, I would like a regex which matches with decimal numbers.
允许的类型:
12 1.3234 0.3423434 23423.12不允许的类型:
0012 12.324.12 01.2332 .12 121212.提前感谢您的帮助!
问候!
推荐答案这个正则表达式应该可以完成你的工作.
This regex should do your job.
^(?:[1-9][0-9]*|0)(?:\.[0-9]+)?$演示
- ^ - 字符串的开始
- (?: - 非捕获组的开始
- [1-9][0-9]* - 匹配不以零开头的数字
- |0 - 或者只允许匹配零以允许像 0.3423434 或 0.1 这样的数字
- (?:\.[0-9]+)? - 可选地允许数字中的小数部分
- $ - 字符串结束
- ^ - Start of string
- (?: - Beginning of a non-capture group
- [1-9][0-9]* - Matches a number not starting with a zero
- |0 - Or allows matching only a zero to allow numbers like 0.3423434 or 0.1
- (?:\.[0-9]+)? - Optionally allows a decimal part in the number
- $ - End of string
根据艾伦的建议使用 \d 而不是 [0-9]
Based on Allan's suggestion to use \d instead of [0-9]
如果您的输入只包含英文数字,或者当您只想匹配英文数字时,那么应该首选使用 [0-9] ,原因是更好的性能和广泛的支持正则表达式引擎.
In case your input only contains English numbers, or when you only intend to match English numbers, then using [0-9] should be preferred for reasons like better performance and wide supported of it across regex engines.
但如果您的输入包含来自其他语言的数字,例如印地语 १ २ 等,并且您想匹配任何数字,则 \d 应该是首选而不是 [0-9]
But in case your input contains digits from other languages like Hindi १ २ etc. and you want to match any digits, then \d should be preferred instead of [0-9]
更多推荐
十进制数的正则表达式
发布评论