我想使用preg_match來匹配數字1 - 21.我怎樣才能使用preg_match做到這一點?如果數字大於21,我不想匹配任何東西。PHP preg_match範圍
example preg_match('([0-9][0-1]{0,2})', 'Johnathan 21');
我想使用preg_match來匹配數字1 - 21.我怎樣才能使用preg_match做到這一點?如果數字大於21,我不想匹配任何東西。PHP preg_match範圍
example preg_match('([0-9][0-1]{0,2})', 'Johnathan 21');
從comment above複製:
我建議匹配只是([0-9]{1,2})
(也許裹着\b
,基於輸入格式)並過濾數值後來,在PHP代碼中。請參閱Raymond Chen's thoughts on the subject。
謝謝。我用'\ d +'將數字匹配到數組中,然後我驗證它是在1 - 21之間。 – James 2012-04-07 17:25:24
從字面上看:
preg_match('~ (1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21)$~', 'Johnathan 21');
但也許這是更漂亮:
preg_match('~ ([1-9]|1[0-9]|2[01])$~', 'Johnathan 21');
我不認爲你需要限制正則表達式的有效解決方案,其他方法(例如捕獲正則表達式中的[[0-9] {1,2}'並且之後驗證)可能更容易。 http://blogs.msdn.com/b/oldnewthing/archive/2006/05/22/603788.aspx – DCoder 2012-04-07 17:10:29
@二極管:這應該是一個答案。 – 2012-04-07 17:17:24
是的。我認爲我會更簡單地使用正則表達式。 – James 2012-04-07 17:21:26