0

I am trying out this regex on this page: http://www.regular-expressions.info/javascriptexample.html

where Regex=(?:http:\/\/)?(?:www.)?facebook\.com\/([\w\-\.]*)?

and Subject String = http://www.facebook.com/xxxxxx

This returns me two matches: http://www.facebook.com/xxxxxx and xxxxxx

The same javascript I have embedded in my chrome extension, however there it shows me only one match: 'http://www.facebook.com/' . Any ideas ? Following is the code:

var re = new RegExp("(?:http:\/\/)?(?:www.)?facebook\.com\/(?:profile\.php\?id=(?=\d.*))?([\w\-]*)?"); var m = re.exec("http://www.facebook.com/xxxxx"); if (m == null) { alert("No match"); } else { var s = "Match at position " + m.index + ":\n"; for (i = 0; i < m.length; i++) { s = s + m[i] + "\n"; } alert(s); } 
2
  • In your first example, there aren't really two matches - the first entry is the part of the string that matches the pattern. The second entry is the part within the capturing group. Commented Jun 15, 2011 at 23:07
  • @George : Sorry, but i do not understand. The same is running on that web page and chrome extension. Still the output is different. Commented Jun 15, 2011 at 23:17

1 Answer 1

2

When regexp comes from a string, each backslash should be masked:

var re = new RegExp("(?:http:\\/\\/)?(?:www.)?facebook\\.com\\/(?:profile\\.php\\?id=(?=\\d.*))?([\\w\\-]*)?"); 

In javascript you can also create regexp patterns without strings:

var re = /(?:http:\/\/)?(?:www.)?facebook\.com\/(?:profile\.php\?id=(?=\d.*))?([\w\-]*)?/; 
Sign up to request clarification or add additional context in comments.

1 Comment

+1. I was surprised it didn't throw an exception, but the only thing it seems to have a problem with is the \w in [\w\-]. Since that part of the regex is optional anyway, the match succeeds without consuming the xxxxx part.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.