RegEx to extract array of strings in javascript using match()

Viewed 1354

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"    INTEGER UNIQUE,
        "state" TEXT,
        "title" TEXT,
        "description"   TEXT,
        "price" TEXT,
        "currency_code" TEXT,
        "url"   TEXT,
        PRIMARY KEY("listing_id")

Expected results:

['listing_id', 'state', 'title', 'description', 'price', 'currency_code', 'url']

what I've tried: /(?<!\()(\").+?(\")(?!\ \()/g

3 Answers

Adding Parentheses around the actual string content solves it: (?<!\()(\")(.+?)(\")(?!\ \(), matching group 2.

Live example: http://regexr.com/58m4i

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 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.

Related