Page 1 of 1

Simple RegEXP HELP!

Posted: Fri Apr 29, 2011 2:50 pm
by J0kerz
Hey guys,

I am having trouble with a Javascript regular expression. I am using the match function and results output are wrong.

Here is my code:

Code: Select all

<script language="javascript" type="text/javascript">

string = 'addfriend\.php\?id=1\\\" |||||| addfriend\.php\?id=2\\\" |||||| addfriend\.php\?id=3\\\" ';

result = string.match(/addfriend\.php\?id=(\d*)\\\"/gi);


for (i=0; i < result.length; i++) {


	document.write(result[i] + '<br>');

}


</script>
The result are:

addfriend.php?id=1\"
addfriend.php?id=2\"
addfriend.php?id=3\"


I would like the result to only be:

1
2
3

What is wrong with my code? How could it only select the id number?

Thanks guys!

Re: Simple RegEXP HELP!

Posted: Thu May 05, 2011 3:57 am
by JakeJ
try: '/(?<=addfriend.php\?id=)(.*?)(?=\\)/'

This expression does a positive look-behind for 'addfriend.php\?id=' then find any value, the does a positive look ahead for a slash. The look-ahead and look-behind are excluded from the actual search results.



Please note, I didn't test it.

Re: Simple RegEXP HELP!

Posted: Fri May 06, 2011 1:49 pm
by tr0gd0rr
JavaScript String#match does not work that way. You may be looking for something like PHP's preg_match_all(). This post shows an example. Also check out Prototype JavaScript's String#scan.

Re: Simple RegEXP HELP!

Posted: Fri May 06, 2011 3:16 pm
by McInfo
This is similar in that it does a global match and then local matches.

Code: Select all

var str = 'addfriend\.php\?id=1\\\" |||||| addfriend\.php\?id=2\\\" |||||| addfriend\.php\?id=3\\\" ';
var ids = [];
try {
    str.match(/addfriend\.php\?id=\d+/gi).forEach(function(s){ ids.push(s.match(/\d+/)[0]); });
} catch (e) { /* TypeError */ }
/* ids = ["1", "2", "3"] */
If any of your target browsers do not support Array.forEach(), you can use a loop instead or extend Array.prototype.