RegEx 使用 match() 在 javascript 中提取字符串数组

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

我正在尝试使用 javascript 中的 string.match() 和正则表达式来提取字符串数组。

这是一个示例字符串:

CREATE TABLE "listings" (
        "listing_id"    INTEGER UNIQUE,
        "state" TEXT,
        "title" TEXT,
        "description"   TEXT,
        "price" TEXT,
        "currency_code" TEXT,
        "url"   TEXT,
        PRIMARY KEY("listing_id")

预期结果:

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

我尝试过的: /(?<!\()(\").+?(\")(?!\ \()/g

在实际字符串内容两边加上括号即可解决:(?<!\()(\")(.+?)(\")(?!\ \(),匹配组 2.

实例:http://regexr.com/58m4i

使用

/(?<=CREATE TABLE[^(]*\([^()]*)"([^"]*)"/g

参见proof。该表达式将匹配以 CREATE TABLE ( 开头的双引号之间的字符串和括号以外的任何字符串。

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]));

无需使用的解决方案matchAll

如果需要匹配CREATE TABLE然后获取行首双引号之间的内容:

ip_str.match(/(?<=CREATE TABLE.*^\s*")[^"]+(?=")/gms)

如果CREATE TABLE不需要匹配:

ip_str.match(/(?<=^\s*")[^"]+(?=")/gm)

这里的主要技巧是使用 m 标志将搜索锚定到行首。