views:

60

answers:

4

Anyone help? When I run this I get " invalid quantifier ?<=href= "

var aHrefMatch = new RegExp("(?<=href\=")[^]+?(?=")"); 
var matchedLink = mystring.match(aHrefMatch);

But I know the regular expression is valid.

Any ideas?

+1  A: 

You need to escape the double quotes in the regular expression with the standard backslash:

var aHrefMatch = new RegExp("(?<=href\=\")[^]+?(?=\")");

...or you could just use single quotes to specify the string:

var aHrefMatch = new RegExp('(?<=href\=")[^]+?(?=")');
Steve Harrison
+9  A: 

Javascript does not support lookbehind assertions. It only supports lookahead ones. The error is produced because it assumes the ? is a quantifier for 0 or 1, but there is no element to quantify at the beginning of a subpattern (started by that ( opening parenthesis)

Also, your string seems to be missing a few backslashes, as the double quotes are not escaped there. It should produce a syntax error.

Perhaps this code could help you do what you are trying to achieve:

var match = mystring.match(/href=\"([^\"]*)\"/);
var matchedLink = match[1];
Rithiur
+1 for the only answer to point out *both* problems: lookbehinds and unescaped quotes.
Alan Moore
Yep, have just read another article stating that js does not support lookbehind assertions. Thanks!
Meander365
+1  A: 

Did you mean to escape the quote after the = sign and after the look ahead ?=. Also if you are just trying to match the href="some text" , then you really don't need look behind and look ahead constructs. The following should do just fine

href=\"[^"]+\"

If you are trying to match something else, please elaborate. Thanks

Jasmeet
A: 

Don't really know what you want to do. But if you want to get the link.

var aHrefMatch = new RegExp(/(href\=\")([\w\-\/]+)?(\")/); 
var matchedLink = mystring.match(aHrefMatch)[2];
fredrik
Yeah I need to get the href of the anchor elements in a string. Fredrik your code seems closest but when I run it I get:-illegal charactervar aHrefMatch = new RegExp(href=\"[^"]+\"); \n
Meander365
Make sure that you remove all whitespace, sounds like some illegal char made it it's why in to you copy/paste.If not please paste what mystring looks like.
fredrik
The RegExp constructor takes a string as its first argument. @Meander365, change the `/` at the beginning and end to `"`. Or just use a regex literal, as @Rithiur suggested.
Alan Moore