Tyler Tyler - 4 months ago 20
jQuery Question

Javascript Regex get list of string not in single or double quotes

Hi Guy i have list of string.

Select
id AS "cusId ",
name as 'cusName', gendar as ' Gendar.',
isPaid as " is'Paid ", total, remarks FROM


I need a regex that return me :
Select
id
name
gendar
isPaid
total
remarks
FROM
And aslo ignore comma and 'AS' keyword.

So far from PHP i can use :
preg_match_all

('/(?<![\S"])([^"\'\s]+)(?![\S"])/')
and filter all query keyword later on.

But came to JavaScript there is not look behind in regex.
Any idea? thanks

Answer

You can use a regex that will match what you do not need, and then will capture what you need:

/"[^"]*"|'[^']*'|\s+AS\s+|\s*((?:(?!\sAS\s)[^,\s])+)/gi

See the regex demo

Explanation:

  • "[^"]*" - match a double-quoted substring that has no " inside (replace with "[^"\\]*(?:\\.[^"\\]*)*" if you need to support escaped " inside)
  • | - or
  • '[^']*' - match single-quoted substring having no ' inside (replace with '[^'\\]*(?:\\.[^'\\]*)*' if you need to support escaped ' inside)
  • | - or
  • \s+AS\s+ - "AS" word inside 1+ whitespaces
  • | - or
  • \s* - 0+ whitespaces
  • ((?:(?!\sAS\s)[^,\s])+) - Group 1 capturing one or more symbols other than , and whitespace (see [^,\s])+) that are not starting a sequence of a whitespace + AS + whitespace. It matches any text that is not space+AS+space.

JS demo:

var re = /"[^"]*"|'[^']*'|\s+AS\s+|\s*((?:(?!\sAS\s)[^,\s])+)/gi; 
var str = 'Select id AS "cusId ", name as \'cusName\', gendar as \' Gendar.\', isPaid as " is\'Paid " total , datetime FROM';
var res = [];
while ((m = re.exec(str)) !== null) {
    if (m[1]) { 
        res.push(m[1]); // Add the Capture group 1 to the resulting array
    }
}
document.body.innerHTML = "<pre>" + JSON.stringify(res, 0, 4) + "</pre>";