2016-07-08 62 views
0

我在JavaScript中尋找一個正則表達式或邏輯陷阱以下條件尋找一個正則表達式來滿足以下

If a value begins with a number [space] Street call X 

    5 Eastern 
    500 Eastern 
    25 15th 

..

If NO street number call Y 

    Eastern 
    15th St 
    N Eastern 

任何幫助或方向將是讚賞。

+0

而不是* *尋找一個正則表達式,你爲什麼不嘗試寫* *一個?採取[正則表達式教程](http://www.regular-expressions.info/tutorial.html)。 – nnnnnn

回答

1

這裏就是你要找的正則表達式:

/^\d+\s[A-Z0-9][a-z]+/ 

然後在JS,使用下列方式:

if (/^\d+\s[A-Z0-9]+[a-z]+/.test(value)) { 
    x(); 
} 
else { 
    y(); 
} 

當然value是要測試的字符串。

測試...

/^\d+\s[A-Z0-9]+[a-z]+/.test('5 Eastern') 
// => true 

/^\d+\s[A-Z0-9]+[a-z]+/.test('500 Eastern') 
// => true 

/^\d+\s[A-Z0-9]+[a-z]+/.test('25 15th') 
// => true 

/^\d+\s[A-Z0-9]+[a-z]+/.test('Eastern') 
// => false 

/^\d+\s[A-Z0-9]+[a-z]+/.test('15th St') 
// => false 

/^\d+\s[A-Z0-9]+[a-z]+/.test('N Eastern') 
// => false 
+0

謝謝!我花了近一個小時玩無數組合 –