Making a Regex object that matches a Javascript string. Explain method -


here regular expression "javascript:the parts" book

//make regular expression object matches javascript string. var my_regexp = new regexp("\"(?:\\\\.|[^\\\\\\\"])*\"", 'g'); 

what [^\\\\\\\"] expression matching here?

in javascript, strings surrounded " (or ', regex doesn't support) , \ used escape characters otherwise have different meaning.

now, [^\\\\\\\"] character class characters aren't \ or ". because we're using string literal define regular expression " needs escaping, , because \ has special meaning within both strings , regular expressions need escape them too.

\"        starting characters \\"       escape `\` regex \\\"      escape `"` regex \\\\\\"   escape `\` string \\\\\\\"  escape `"` string 

it's simpler if use ' string, or regex literal. following same.

new regexp("\"(?:\\.|[^\\\\\\\"])*\"", "g"); new regexp('"(?:\\.|[^\\\\\\"])*"', 'g'); /"(?:\.|[^\\\"])*"/g 

in fact, " doesn't have special meaning in regular expression, escaping not necessary.

/"(?:\.|[^\\"])*"/g 

also note . isn't either \ or ", | construct pointless. guess error, , it's intended \\. - i.e. \ followed character. require 4 \ in original, not two. without correction, expression won't match strings "ab\\c".

if want support ' things going complicated, , should use simple char-by-char parser, rather regular expression.

regexp reference


Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

php - MySQLi multi_query results for later use -