1

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

Swader
  • 11,387
  • 14
  • 50
  • 84

1 Answers1

5

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

Jonathon Bolster
  • 15,811
  • 3
  • 43
  • 46
  • Brilliant, that was it! The ID is always served in this exact format, and I needed the number only. This string removes the last brace perfectly and gives me exactly what I want. Thank you very much! – Swader Dec 21 '10 at 09:12
  • or try: RegExp(/[0-9]+$/g) --- $ mean find last digit from string – user956584 Jan 02 '12 at 07:32