具有固定總位數的十進制正則表達式

[英]regular expression for decimal with fixed total number of digits


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


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/05/06/724df8d42f2d0b88295d8d42dc883703.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com