开发者

Regular Expressions and JavaScript: Find digits in last part of string

I need to extract the ID number from a string. The results are given to me in the following format: "Something with some kind of title (ID: 300)" "1, 3, 4 - Something that starts with numbers (ID: 400)" etc..

These values are passed into javascript, which then needs to extract the ID number only, i.e. 300, or 400 in the above example.

I am still struggling with regex, so any help is greatly appreciated. I can easily do this with string operations, but would really like to 开发者_如何学运维get my feet wet with RegEx on some actual examples I can use. The online tutorials I've read so far have proven fruitless.

Thank you


If your number is always in the form (ID: ###) then \(ID: ([0-9]+)\) should do as your regex. The brackets around ID and the number are escaped, otherwise they would be considered a matching group (as the brackets around [0-9]+ are. The [0-9] means check for any character than is between 0 and 9 and the + means 'one or more of'.

var regex = new RegExp(/\(ID: ([0-9]+)\)/);
var test = "Some kind of title (ID: 3456)";

var match = regex.exec(test);
alert('Found: ' + match[1]);

Example: http://jsfiddle.net/jonathon/FUmhR/

http://www.regular-expressions.info/javascript.html is a useful resource

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜