0

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 ]

3
  • i even tried str.match(tag+"(\s*=\s*)((['\"]*)(.+?)(['\"]*)\1)"); but the result is showing null Commented Apr 9, 2012 at 6:21
  • 1
    what language is this code for? Commented Apr 9, 2012 at 6:21
  • I am using this in javascript Commented Apr 9, 2012 at 6:22

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1
  • 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"]

5 Comments

What is your example, which result in null?
var m="img"; s1 = document.createElement(m); s1.src="cdac.com"; i am retrieving m successfully and for getting the tag name i am using the above expression which is resulting null
Excuse me, but I don't see the code, where you're using this expression.
var m="img"; s1 = document.createElement(m); s1.src="cdac.com";var y=str.match(tag+"(\s*=\s*)((['\"]*)(.+?)\3)");
Maybe, you understood me wrong. I want to see not data, but code, how you are using it. If you mean string with that js code, it is working, i.e. matching m="img".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.