user1275375
user1275375

Reputation: 1391

In regular expression: SyntaxError: Unexpected token ]

I used the following expression

str.match(tag+"(\s*=\s*)((['"]*)(.+?)(['"]*)\1)");

where str is the string to be matched with and tag is a variable

For example the above expression should match

m="img"
m='img'

where tag=m;
But at the above mentioned lined I'm getting

SyntaxError: Unexpected token ]

Upvotes: 0

Views: 1053

Answers (2)

kirilloid
kirilloid

Reputation: 14304

  • As was stated, quotes should be escaped.
  • backreference should be escaped too.
  • once you use backreference, second group with quote is not needed,
  • it is third parethesis group, which contain quotes, hence you need \3, not \1
  • and hardly you need to match any amount of quotes like: m = '''img'''

Taking all these points into account, one may get the following solution:

var tag = 'm';
"m='img'".match(tag+"(\s*=\s*)((['\"]?)(.+?)\\3)")
// ["m='img'", "=", "'img'", "'", "img"]

Upvotes: 1

dexametason
dexametason

Reputation: 1133

If you remove /1 from the end of the regexp, it works for m="img":

m(\s*=\s*)((['\"]*)(.*)(['\"]*))

"\1" is replaced with the value of the first subpattern within the pattern so if you would like to match m="img";m='img' you should use the following:

(m\s*=\s*)((['\"]*)(.*)(['\"]*)\1)

where m is your tag variable.

EDIT:
you can test your javascript regexps here.

Upvotes: 2

Related Questions