十进制或小数的正则表达式 [英] Regex for decimal or fraction

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

问题描述

现在我有一个正则表达式,它在其中检查字符串是否为十进制格式:

Right now I have a regex where it checks if the string in a decimal format or not:

-?\\d+(?:.\\d+)//any positive or negative number, including decimals

如果我想为一个分数创建一个正则表达式,它也可以由小数组成,例如:

If I wanted to create a regex for a fraction, which may also consist of decimals, such as:

  • 3.1/2.6
  • 1.00/5.00

以下内容有效吗?

 -?\\(d+(?:.\\d+)|d+(?:.\\d+)/d+(?:.\\d+))//a decimal OR a fraction(including decimals)

推荐答案

您可以使用此正则表达式来支持正/负整数,带可选小数部分的小数:

You can use this regex to support positive/negative integers, decimals with optional fractional part:

-?\\b\\d+(?:\\.\\d+)?(?:/\\d+(?:\\.\\d+)?)?\\b

RegEx演示

或者,如果您使用Java的 String#matches()方法,请使用此正则表达式:

Or if you're using Java's String#matches() method then use this regex:

-?\\d+(?:\\.\\d+)?(?:/\\d+(?:\\.\\d+)?)?

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

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