對不起,我可能愚蠢的問題,但我想拉在一起的正則表達式將允許:爲小數或正則表達式空白
小數點前有1個或2個號碼的數字,和0-6號小數點後面。但是,如果需要,我還需要允許該字段爲空。
有效例子
0.952321
1.20394
12.12
25
Blank
無效的例子
123.45678
1.1234567
請誰能幫助?
對不起,我可能愚蠢的問題,但我想拉在一起的正則表達式將允許:爲小數或正則表達式空白
小數點前有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
感謝您的幫助 – 2010-03-24 15:02:48
@Phil P:如果其中一個答案解決了您的問題,upvote和/或接受最佳答案。 – AxelEckenberger 2010-03-24 15:06:03
您應該提供正在使用正則表達式的語言,許多功能允許您創建更多可讀的表達式。這裏是一個故障安全POSIX regex:
^([0-9]{1,2}\.[0-9]{0,6})?$
如果小數部分是可選的,你可以使用
^([0-9]{1,2}(\.[0-9]{1,6})?)?$
+1不匹配以小數結尾的數字(例如「25.」)。雖然在問題中沒有明確說明,但我會假設這一要求。 – Mark 2010-03-24 18:24:57
閱讀字裏行間,我擴大了可接受的輸入的定義,而不是和假定您只想以所描述的格式捕捉數字。
例如,這些數字將捕獲的數字右邊,都是可以接受的輸入:
"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
一般來說,ie無限小數位:
^-?(([1-9]\d*)|0)(.0*[1-9](0*[1-9])*)?$
我會用其中的一個:
要匹配所有的小數點:
(\d+\.\d+){0,1}
之前在數量上較特別/後點,嘗試/與任何這些變化:
(\d+\.\d{2}){0,1}
(\d{4}\.\d{2}){0,1}
你使用什麼語言? – miorel 2010-03-24 15:00:09
你是什麼意思的空白? – PierrOz 2010-03-24 15:01:41