带可选小数点的十进制数的正则表达式

Regex for decimal number with optional decimal point

本文关键字:十进制数 正则表达式 小数点      更新时间:2023-09-26

我的要求是测试粘贴的数据,如果失败就不要粘贴。

Regex: /'d{0,4}(['.|',]'d{0,2})?/

使用数据:

1.2 tests true
1.2.3 test true as well

要求是

min 0小数点前最多4位
小数点可以是点或逗号
最小1如果有小数点,小数点后最多3位。

我已经试过了,但不工作。
如有任何帮助,不胜感激。

小提琴

从您的需求

/^'d{0,4}(?:[.,]'d{1,3})?$/
  1. ^:行起始
  2. 'd{0,4}: 0 - 4位
  3. [.,]:匹配点或逗号
  4. 'd{1,3}: 1 - 3位
  5. (?: ... ):非捕获组
  6. (something)?组可以出现零次或一次
  7. $: End of line

input:valid {
  color: green;
  font-weight: bold
}
input:invalid {
  color: red;
}
<input type="text" pattern="'d{0,4}(?:[.,]'d{1,3})?" />