[英]Regular Expression for Decimal or Blank
對於這個可能很愚蠢的問題,我很抱歉,但我試圖將正則表達式放在一起,這樣可以:
小數點前有1或2個數字,小數點后有0-6個數字的數字。 但是,如果需要,我還需要允許該字段為空白。
有效示例
0.952321
1.20394
12.12
25
Blank
無效的示例
123.45678
1.1234567
請任何人可以幫忙嗎?
^(?:\d{1,2}(?:\.\d{0,6})?)?$
應該做的伎倆。
\d matches any digit
{n,m} specifies the number of occurrences
(?: ) creates an anonymous group
^ specifies the start of the string
$ the end of the string
? means the group is optional
^(?:|\\d{1,2}(?:\\.\\d{0,6})?)$
管道前面的部分是空白的。 匹配一個或兩個數字之后的部分,可選地后跟一個句點和最多六個數字。 ?:
所以除非需要,否則我們不使用捕獲組。
希望這可以幫助!
您應該提供使用正則表達式的語言,許多語言具有允許您創建更易讀的表達式的功能。 這是一個故障安全的POSIX正則表達式 :
^([0-9]{1,2}\.[0-9]{0,6})?$
如果小數部分是可選的,您可以使用
^([0-9]{1,2}(\.[0-9]{1,6})?)?$
一般來說,即無限小數位:
^-?(([1-9]\\d*)|0)(.0*[1-9](0*[1-9])*)?$
我會使用其中一個:
要匹配所有小數:
(\d+\.\d+){0,1}
要在點之前/之后更具體,請嘗試使用以下任何一項進行/ variate:
(\d+\.\d{2}){0,1}
(\d{4}\.\d{2}){0,1}
^(\d{1,2}(\.\d{1,6})?)?$
在線之間閱讀,我擴展了可接受輸入的定義而不是假設您只想捕獲所描述格式的數字。
例如,這些數字將作為右邊的數字捕獲並且都是可接受的輸入:
"0.952321 " 0.952321 (trailing spaces stripped)
" 1.20394 " 1.20394 (leading and trailing spaces stripped)
"12.12" 12.12 (no leading or trailing spaces)
"12.123 " 12.123
" .1234 " .1234 (no leading digit -- start with decimal)
"25" 25 (no decimal)
" " " " ? (space. space captured or not)
"12." 12. (1 or 2 digits, decimal, no numbers after decimal)
不行輸入:
"." just a decimal
"123456789" more than 2 digits lefthand
123 "" ""
123.45678
1.1234567 more than 6 digits right hand
[a-zA_Z] not a digit...
所以,鑒於此,這個正則表達式將會這樣做:
/^\s*( # beginning of string and strip leading space
| \d{1,2}\.? # 1 or 2 digits with optional decimal
| \d{0,2}\.\d{1,6} # 0,1, 2 digits with a decimal with digits
| \s+ # remove if you do not want to capture space
)\s*$ # trailing blanks to the end
/x
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.