2011-05-16 71 views
0

我想在這樣的字符串,在方括號中提取號碼:簡單的正則表達式模式,提取號碼

"Item5Line[14].Id" 

我至今導致在Javascript中的錯誤:

index = Id.attr('name').match(/\[\d\d?\d?\]); 

我很新的正則表達式,所以請溫柔:)提前

謝謝!

回答

2

嘗試:index = Id.attr('name').match(/\[(\d+)\]/);

然後你就可以在索引1

+0

謝謝喬希。我是(像下面提到的每個人)錯過了關閉「/」。這個表達當然更清晰。我喜歡這個幫助! – 2011-05-16 18:07:09

+0

不客氣,很高興幫助。 – 2011-05-16 18:29:21

+0

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp涵蓋了正則表達式。你可能也想看到String對象(match())。如果你沒有意識到使用(),當你得到你的「索引」值時,它實際上是一個數組。該數組的元素按照左paren的順序匹配嵌入在正則表達式中的括號對。因此,index [0]以字符串的形式給出完整匹配,index [1]給出由括號內的部分(即「14」)組成的字符串。 嘗試url:javascript:index =/hell(owo)rld/.exec(「helloworld」);警報(指數[1]); – 2011-05-16 18:54:26

2

它看起來像你缺少收盤/在你的正則表達式

index = Id.attr('name').match(/\[\d\d?\d?\]/); 
             ^need this closing/

工作樣本:http://jsfiddle.net/CGnUz/

此外,@Josh M.具有較好的正則表達式。

1
index = Id.attr('name').match(/\[\d\d?\d?\]); 

你忘了在末尾添加/拔出了比賽。