RegEx To Extract Array Of Strings In Javascript Using Match()
I'm trying to use string.match() in javascript with a regular expression to extract an array of strings. Here is a sample string: CREATE TABLE 'listings' (         'listing_id'
Solution 1:
Use
/(?<=CREATE TABLE[^(]*\([^()]*)"([^"]*)"/g
See proof. The expression will match strings between double quotes preceded with CREATE TABLE ( and any strings other than parentheses.
JavaScript:
const regex = /(?<=CREATE TABLE[^(]*\([^()]*)"([^"]*)"/g;
const str = `CREATE TABLE "listings" (
        "listing_id"    INTEGER UNIQUE,
        "state" TEXT,
        "title" TEXT,
        "description"   TEXT,
        "price" TEXT,
        "currency_code" TEXT,
        "url"   TEXT,
        PRIMARY KEY("listing_id")`;
const matches = str.matchAll(regex)
console.log(Array.from(matches, x => x[1]));Solution 2:
Adding Parentheses around the actual string content solves it: (?<!\()(\")(.+?)(\")(?!\ \(), matching group 2.
Live example: http://regexr.com/58m4i
Solution 3:
Solution without having to use matchAll
If you need to match CREATE TABLE and then get the content between double quotes at the start of line:
ip_str.match(/(?<=CREATE TABLE.*^\s*")[^"]+(?=")/gms)
If CREATE TABLE doesn't need to be matched:
ip_str.match(/(?<=^\s*")[^"]+(?=")/gm)
The main trick here is to use m flag to anchor the search to start of line.
Post a Comment for "RegEx To Extract Array Of Strings In Javascript Using Match()"