PrimeLens
PrimeLens

Reputation: 2717

what regular expression would I use to retrieve the digits that follow this string?

I'm using jQuery to retrieve the class attribute and I need to get the a substring of the digits that follow the substring "position"

for example "position7 selected" I need to retrieve "7"

for example "navitem position14 selected" I need to retrieve "14"

I started writing:

$(this).attr('class').match(/(\d+)$/))

But I am getting lost with the regular expression, any help much appreciated. I actually really really like regular expressions but I'm still learning!

update due to first answer: there might be another group of digits which I need to ignore For example "navitem2 position14 selected" I need to retrieve "14"

Upvotes: 0

Views: 83

Answers (4)

ComfortablyNumb
ComfortablyNumb

Reputation: 3501

  var r = "aaa 1 bb 2 position 113 dd".match(/position\s*(\d+)/)
  if (r instanceof Array )
      return r.pop()

Upvotes: 1

Bruno
Bruno

Reputation: 5822

You can replace everything that is not a number

str.replace(/\D/g,"");

If other numbers are present in the string you can still use replace

str.replace(/^.*position(\d+).*$/,"$1");

However, you may want to go for one of the other regex expressions in the other answers.

Upvotes: 2

Martin Ender
Martin Ender

Reputation: 44259

Your attempt has two problems. The first is you anchor it to the end of the string with $. So instead of giving you the digits after position it will give you digits at the endof the string. At the same time you don't mention position at all. What you are looking for is this:

var matches = str.match(/position(\d+)/);

Now matches will be

["position14", "14"]

Upvotes: 3

Tom Smilack
Tom Smilack

Reputation: 2075

"navitem position14 selected".match(/position(\d+)/)[1]

The call returns ["position14", "14"], so the [1] element is 14.

You're on the right track with the (\d+), it will match a contiguous group of digits. This just says only match that group when it directly follows the literal string "position".

Upvotes: 4

Related Questions