Forum Moderators: open

Message Too Old, No Replies

RegEX: multiple occurrence of matches

to return multiple html links of given page

         

kadnan

8:55 pm on Feb 18, 2008 (gmt 0)

10+ Year Member



i am using followin code to return all links within a string:


var re = new RegExp(document.t.regex.value);
var m = re.exec(document.t.myString.value);
if (m == null) {
alert("No match");
} else {

alert("No of matches= "+m.length);

var s = "Match at position " + m.index + ":\n";
for (i = 0; i < m.length; i++) {
s = s + m[i] + "\n";
alert(m[i] );
}
//alert(s);
}

input string consist of two HTML links but its not returning all links. where am I doing wrong?

Dabrowski

9:18 pm on Feb 18, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hmmm, I prefer the syntax as:
var m = document.t.myString.value.match( re);

But that shouldn't make any difference.

Firstly, I believe you have to specify the 'g' modifier to make it match more than once, like this:
var re = new RegExp( document.t.regex.value, "g");

And you are assuming that m[...] refers to the match occurance, however that refers to the strings captured in the ()'s in your regex, if any.

Not sure of the global match syntax in JS. In Perl you'd do a while loop and keep calling match.

It would be helpful to see your regex, I see you have it in a form, is this just so you can mess with it on the fly? Maybe you could give me an example of the string you're trying to match on?

kadnan

5:54 am on Feb 19, 2008 (gmt 0)

10+ Year Member



my mistake that I didn't mention RegEX


<a.+?href="([^"]+?)"

yes I am using "g" switch in my code.

mehh

9:31 am on Feb 19, 2008 (gmt 0)

10+ Year Member



I think the exec function quits after the first match, try Dabrowski's suggestion of
var m = document.t.myString.value.match(re);

Dabrowski

5:10 pm on Feb 19, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hmmm, your regex is strange too!

<a.+?href="(.*?)"

Instead of matching [^"] (not a quote), matching any character until the next quote is easier.

I find this tool absolute gold dust as I use Perl a lot and you can't use Perl without a lot of Regexing.
[weitz.de...]

Anyways, I can't see what's wrong if you're using the "g", although it was not present in your example code. I would try repeatedly calling .match until you get a null return.