十进制数的正则表达式

编程入门 行业动态 更新时间:2024-10-23 17:25:52
本文介绍了十进制数的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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]

更多推荐

十进制数的正则表达式

本文发布于:2023-11-06 06:31:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562942.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:十进制数   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!