Very weird regex result in javascript

I am not very good at regular expression, but an illogical thing happens:
I checked the regular expression syntax with this script: http://jsfiddle.net/BcQfQ/2/ and then replaced it \dwith another regular expression to check the url from here : http://daringfireball.net/2010/07/improved_regex_for_matching_urls and it doesn't work: http://jsfiddle.net/bNHQs/2/ . And the strangest thing is that when you copy the regular expression and paste it into the text box (and then write textbox.value to the code), everything is fine: http://jsfiddle.net/6uAQG/2/ .

Broken regex code:

var reg=/\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?ยซยป""โ€˜โ€™]))/;
var str="2";
if(str.match(reg))alert("test:true");
else alert("test:false");

How can I write a regular expression in code to make it work?

+3
source share
1 answer

You need to avoid delimiters ("/") using backslashes. Separators mark the beginning and end of an expression. You can use a slash only when you escape it with a backslash. The following expression should work:

var reg=/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?ยซยป""โ€˜โ€™]))/;
+5
source

All Articles