Logan Best
Logan Best

Reputation: 501

JS Regex problems

I'm trying to match a Number in between a set of straight brackets, example:

Match the 0 in actionFields[actionFields][0][data[Report][action]]

This is what I have so far and I keep getting null.

var match, matchRegEx = /^\(?\[(\d)\]\)$/;
nameAttr = "actionFields[actionFields][0][data[Report][action]]", 
match = matchRegEx.exec(nameAttr);

Upvotes: 0

Views: 67

Answers (3)

Rogel Garcia
Rogel Garcia

Reputation: 1915

If there's only one number /\d+/ You can test only for the number

Upvotes: 1

CanSpice
CanSpice

Reputation: 35828

If you look at your regular expression, you're matching the beginning of the string, zero or one (, then a [, then a \d, then a ], then a ), then the end of the string.

You should just be able to get away with /\[(\d)\]/, unless you're expecting the [0] construct to show up elsewhere in your string.

Here's a RegexPal showing this.

Upvotes: 3

fge
fge

Reputation: 121840

Your regex should be:

\[(\d+)\]

and capture the first group.

One problem with your regex is that it is anchored at the beginning of input (^) and at the end $.

Upvotes: 1

Related Questions