十进制数的正则表达式 [英] Regex expression for decimal number

查看:47
本文介绍了十进制数的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我使用正则表达式吗?基本上,我想要一个与十进制数匹配的正则表达式.

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.34234340.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]

这篇关于十进制数的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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