2010-03-24 16 views
5

對不起,我可能愚蠢的問題,但我想拉在一起的正則表達式將允許:爲小數或正則表達式空白

小數點前有1個或2個號碼的數字,和0-6號小數點後面。但是,如果需要,我還需要允許該字段爲空。

有效例子

0.952321 
1.20394 
12.12 
25 
Blank 

無效的例子

123.45678 
1.1234567 

請誰能幫助?

+0

你使用什麼語言? – miorel 2010-03-24 15:00:09

+0

你是什麼意思的空白? – PierrOz 2010-03-24 15:01:41

回答

1

^(?:|\d{1,2}(?:\.\d{0,6})?)$

管前部相匹配的空白。之後的部分匹配一個或兩個數字,可選地後跟一個句點和最多六位數字。 ?:所以我們不使用捕獲組,除非需要。

希望這會有所幫助!

+0

在你的正則表達式中。是強制性的:它不匹配25上面的例子 – PierrOz 2010-03-24 15:00:12

+0

感謝這個隊友 – 2010-03-24 15:02:02

+0

@PierrOz,是的我重新檢查了問題,並修復它:)謝謝! – miorel 2010-03-24 15:03:33

11
^(?:\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 
+0

感謝您的幫助 – 2010-03-24 15:02:48

+3

@Phil P:如果其中一個答案解決了您的問題,upvote和/或接受最佳答案。 – AxelEckenberger 2010-03-24 15:06:03

2

您應該提供正在使用正則表達式的語言,許多功能允許您創建更多可讀的表達式。這裏是一個故障安全POSIX regex

^([0-9]{1,2}\.[0-9]{0,6})?$ 

如果小數部分是可選的,你可以使用

^([0-9]{1,2}(\.[0-9]{1,6})?)?$ 
+0

+1不匹配以小數結尾的數字(例如「25.」)。雖然在問題中沒有明確說明,但我會假設這一要求。 – Mark 2010-03-24 18:24:57

0
^(\d{1,2}(\.\d{1,6})?)?$ 
+0

您的正則表達式會匹配一個8位整數。 – miorel 2010-03-24 15:10:29

+0

@Miorel:啊哈哈你是對的:) 我想我們會在末尾有同樣的一個:) – PierrOz 2010-03-24 15:28:48

+0

也許;)我喜歡你如何處理空白選項,我應該改變我的! – miorel 2010-03-24 15:46:53

0

閱讀字裏行間,我擴大了可接受的輸入的定義,而不是和假定您只想以所描述的格式捕捉數字。

例如,這些數字將捕獲的數字右邊,都是可以接受的輸入:

"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 
0

一般來說,ie無限小數位:

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

0

我會用其中的一個:

要匹配所有的小數點:

(\d+\.\d+){0,1} 

之前在數量上較特別/後點,嘗試/與任何這些變化:

(\d+\.\d{2}){0,1} 
(\d{4}\.\d{2}){0,1}