2017-04-18 33 views
-1

我:需要這個正則表達式來檢查3個小數位嗎?

^-?[0-9]\d*(\.\d+)?$ 

但需要它,只允許最多3位小數。所以允許值包括:

+10.123 

-10.123 

10.123 

10 

+10 

-10 

10.1 

10.12 

不允許:

10.1234 

10.123% 

通知/提示理解表達MODS的。

在此先感謝。

+1

這裏:'^ [ - +] \ d +(\ \ d {1,3})?$'' –

回答

1
^[+-]?\d+(\.\d{1,3})?$ 

說明: enter image description here

見這裏:https://www.debuggex.com/r/BbCBL5pQWLxsD4a6

^ asserts position at start of a line 
    Match a single character present in the list below [+-]? 
    ? Quantifier — Matches between zero and one times, as many times as possible, 
        giving back as needed (greedy) 
    +- matches a single character in the list +- (case sensitive) 
    \d+ matches a digit (equal to [0-9]) 
     + Quantifier — Matches between one and unlimited times, as many times as possible, 
        giving back as needed (greedy) 
    1st Capturing Group (\.\d{1,3})? 
    ? Quantifier — Matches between zero and one times, as many times as possible, 
        giving back as needed (greedy) 
    \. matches the character . literally (case sensitive) 
    \d{1,3} matches a digit (equal to [0-9]) 
    {1,3} Quantifier — Matches between 1 and 3 times, as many times as possible, 
         giving back as needed (greedy) 
    $ asserts position at the end of a line 

說明來自:https://regex101.com/]

+0

@WiktorStribiżew在您評論之前,我正在創建樣本。只有我在原來的錯誤中改變的是{0,3}到{1,3}。 –

+0

@WiktorStribiżew現在有。 –

+0

@dasblinkenlight在線網站爲兩者生成相同的圖片。 –

2

除了*+元字符,它指定無限重複的說明,正則表達式允許您將在比賽用一些具體的限制{a,b}構造。在此,a是所需的最小匹配數,而b是最大值。 ab均爲,包括

既然你需要搭配最多三個數字至少一個,你需要\d{1,3}更換\d+

^[+-]?[0-9]\d*(\.\d{1,3})?$ 

優化:在手工作正則表達式,您可以通過更換[0-9]優化與另一\d,和 「摺疊」 成\d*通過使用\d+

^[+-]?\d+(\.\d{1,3})?$ 
+0

真的很感謝你的答案,只是可以打勾2個答案!謝謝。 – SamJolly

0
^(?!0\d)\d*   
(\.\d{1,4})?$ 
+1

只有代碼答案是不滿意的。請提供解釋,而不僅僅是原始代碼轉儲。 – mason

+0

請添加額外的上下文爲什麼以及如何回答這個問題。 –