2012-08-05 22 views
-2

我試圖匹配包含1至3的數字串,正則表達式匹配的數字和空間

例如:

1 
2 
123 
    3 

這就是我嘗試,

[\s]?[0-9]{1,3}[\s]? 

這是匹配,

123 ->a space after 123 
+3

有什麼問題嗎?這是什麼語言/平臺? – Oded 2012-08-05 19:57:47

+0

Java。我應該能夠匹配1到3位數,當我嘗試時,它匹配123space – FirmView 2012-08-05 19:59:38

+1

所以,字符串應該包含1-3位數字(0-9)和_nothing_否? – Oded 2012-08-05 20:01:38

回答

2

你的問題還不清楚,但似乎你正在尋找一個字符串

  • 正是長3個字符
  • 僅包含數字和空格
  • 至少包含一個數字

在這種情況下,正則表達式是^(?=.*\d)[\d\s]{3}$。作爲Java字符串:"^(?=.*\\d)[\\d\\s]{3}$"

說明:

^   # Start of string 
(?=.*\d) # Assert that there is at least one digit in the string 
[\d\s]{3} # Match 3 digits or whitespace characters 
$   # End of string 
+0

是的,它的工作原理。謝謝。但是,我不確定,我的問題還不清楚,我已經給出了字符串應該匹配的確切示例。不清楚爲什麼它被拒絕投票。 – FirmView 2012-08-05 20:34:21

+0

我已經upvoted你的 – FirmView 2012-08-05 20:35:31

+0

這不是我downvote,但你要求「一個包含1到3位數的字符串」,這是一個條件滿足像「」a1b2c3「或」「3 21」等字符串等 - 事實上,你有五個不同的答案,所有這些答案都以不同的方式解釋你的問題,應該明確說明問題沒有明確定義。 – 2012-08-05 20:43:09

0

你可以在你的正則表達式引擎中使用單詞邊界元字符嗎?試試這個:\b\d{1,3}\b

+0

這應該是一個評論。 – Oded 2012-08-05 19:59:26

1

這應該爲你

^\\d{1,3}$工作。

說明

"^" +  // Assert position at the beginning of the string 
"\\d" + // Match a single digit 0..9 
"{1,3}" + // Between one and 3 times, as many times as possible, giving back as needed (greedy) 
"$"  // Assert position at the end of the string (or before the line break at the end of the string, if any) 
+0

如果有空間,則不匹配 – FirmView 2012-08-05 20:15:02

+0

@FirmView對問題的準確要求不明確。你想匹配一個空間還是你沒有? – 2012-08-05 20:27:56

0

來匹配到3位,與前導空白任何量和沒有結尾的空白圖案,將是:^\s*\d{1,3}$

這將匹配:

1 
2 
123 
    3 

但是不匹配 「123」,並在後面加上一個空格。