...

View Full Version : Complex Regular Expression



TNO
01-16-2009, 02:30 PM
I've been trying to figure out how to write a regular expression to match a regular expression literal, but am having issues with false positives. Here's what I have currently:

/^(?:\/((?:\\.|\[(?:\\.|[^\]])*\]|[^\/])+)\/([gimy]*))/i

and here is an example of a string it gives a false positive on:

/ 2;
//comment
var b = /\n/g;

Any thoughts on what I may be doing wrong with this regular expression?
(FYI: The leading portions of the input string are removed as matches are found, which is why the division operator is now the first character in the input string).

As always, any insight is appreciated

mrhoo
01-16-2009, 04:09 PM
It depends on what you are doing, but I use this expression when I want to sequester regular expressions from a code formatting routine-
var Rx= /(^|[\(\=\:\[,] *)((\/([^\/]+\/))[gim]*)/g;

To return the reg exps in a string, like a file's text or json output, you could do something like this-


var getRx= function(str){
str= str.split(/\r?\n/);
var A= [], Rx, i= 0, s;
var Rx= /(^|[\(\=\:\[,] *)((\/([^\/]+\/))[gim]*)/g;
while(str.length){
s= str.shift();
var M;
while(s && (M= Rx.exec(s))!= null){
A.push(M[2]);
}
}
return A;
}

TNO
01-16-2009, 04:33 PM
hmm, doesn't look like that works either:

http://regexpal.com/

(^|[\(\=\:\[,] *)((\/([^\/]+\/))[gim]*)
------------------------------------------------------------------------
/ 2;
//comment
var b = /\n/g;

TNO
01-16-2009, 05:08 PM
Some more examples of failed matches and what I'm looking for in bold:

var b = /\n/g;
var re = /\n///comment
var re2 = /\//
var NAME = /^[a-z_$][\w$]*/i,
//comment

TNO
01-16-2009, 09:31 PM
Problem solved:

/^\/((?![*\/])(?:\\\/|[^\n\r\u2028\u2029\/])+[^\n\r\u2028\u2029\\])\/([gimy]*)/

credit: http://www.webdeveloper.com/forum/showpost.php?p=969394&postcount=8



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum