Ben Finkel
Ben Finkel

Reputation: 4803

Simple Regular Expression pattern, extract numbers

I'd like to extract the number(s) from in between the square brackets in a string like this:

"Item5Line[14].Id"

What I have so far causes an error in Javascript:

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

I'm very new to regular expressions, so please be gentle :)

Thanks in advance!

Upvotes: 0

Views: 1656

Answers (3)

Jose_X
Jose_X

Reputation: 1094

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

You forgot to add the / at the end.

Upvotes: 1

Josh M.
Josh M.

Reputation: 27781

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

Then you can pull out the match at index 1.

Upvotes: 2

mellamokb
mellamokb

Reputation: 56769

It looks like you are missing the closing / in your regular expression

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

Working sample: http://jsfiddle.net/CGnUz/

Also, @Josh M. has a better regular expression.

Upvotes: 2

Related Questions