具有固定总位数的十进制正则表达式

时间:2021-04-29 21:41:57

Is there a way to write regular expression that will match strings like

有没有办法编写匹配字符串的正则表达式

(0|[1-9][0-9]*)\.[0-9]+

but with a specified number of numeric characters. for example: for 3 numeric characters it should match "0.12", "12.3" but not match "1.234" or "1.2". I know I can write it something like

但具有指定数量的数字字符。例如:对于3个数字字符,它应匹配“0.12”,“12.3”但不匹配“1.234”或“1.2”。我知道我可以这样写

(?<![0-9])(([0-9]{1}\.[0-9]{2})|([1-9][0-9]{1})\.[0-9]{1})(?![0-9])

but that becomes quite tedious for large number of digits.

但对于大量数字而言,这变得相当繁琐。

(I know I don't need {1} but it better explains what I'm doing)

(我知道我不需要{1}但是它更好地解释了我在做什么)

2 个解决方案

#1


^(?=[\d.]{4}$)\d+\.\d+$

You can try this for 3 digits.Can be extended for more.See demo.

你可以尝试3位数。可以扩展更多。参见演示。

https://regex101.com/r/bN8dL3/4

or

 \b(?=[\d.]{4}\b)\d+\.\d+\b

If you dont want anchors.

如果你不想要锚。

#2


You can match them with adding alternatation:

您可以通过添加替换来匹配它们:

\b(?:[0-9]\.[0-9]{2}|[1-9][0-9]\.[0-9])\b

Then, you won't need any start/end string/line anchors.

然后,您将不需要任何开始/结束字符串/行锚点。

See demo

#1


^(?=[\d.]{4}$)\d+\.\d+$

You can try this for 3 digits.Can be extended for more.See demo.

你可以尝试3位数。可以扩展更多。参见演示。

https://regex101.com/r/bN8dL3/4

or

 \b(?=[\d.]{4}\b)\d+\.\d+\b

If you dont want anchors.

如果你不想要锚。

#2


You can match them with adding alternatation:

您可以通过添加替换来匹配它们:

\b(?:[0-9]\.[0-9]{2}|[1-9][0-9]\.[0-9])\b

Then, you won't need any start/end string/line anchors.

然后,您将不需要任何开始/结束字符串/行锚点。

See demo