我試圖匹配包含1至3的數字串,正則表達式匹配的數字和空間
例如:
1
2
123
3
這就是我嘗試,
[\s]?[0-9]{1,3}[\s]?
這是匹配,
123 ->a space after 123
我試圖匹配包含1至3的數字串,正則表達式匹配的數字和空間
例如:
1
2
123
3
這就是我嘗試,
[\s]?[0-9]{1,3}[\s]?
這是匹配,
123 ->a space after 123
你的問題還不清楚,但似乎你正在尋找一個字符串
在這種情況下,正則表達式是^(?=.*\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
這應該爲你
^\\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)
如果有空間,則不匹配 – FirmView 2012-08-05 20:15:02
@FirmView對問題的準確要求不明確。你想匹配一個空間還是你沒有? – 2012-08-05 20:27:56
來匹配到3位,與前導空白任何量和沒有結尾的空白圖案,將是:^\s*\d{1,3}$
。
這將匹配:
1
2
123
3
但是不匹配 「123」,並在後面加上一個空格。
有什麼問題嗎?這是什麼語言/平臺? – Oded 2012-08-05 19:57:47
Java。我應該能夠匹配1到3位數,當我嘗試時,它匹配123space – FirmView 2012-08-05 19:59:38
所以,字符串應該包含1-3位數字(0-9)和_nothing_否? – Oded 2012-08-05 20:01:38