我试图在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
使用
/(?<=CREATE TABLE[^(]*([^()]*)"([^"]*)"/g
见证明。表达式将匹配以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]));
在实际字符串内容周围添加括号可以解决问题:(?<!()(")(.+?)(")(?! ()
,匹配组2。
现场示例:http://regexr.com/58m4i
无需使用matchAll
的解决方案
如果您需要匹配CREATE TABLE
,然后获取行开头双引号之间的内容:
ip_str.match(/(?<=CREATE TABLE.*^s*")[^"]+(?=")/gms)
如果CREATE TABLE
不需要匹配:
ip_str.match(/(?<=^s*")[^"]+(?=")/gm)
这里的主要技巧是使用m
标志将搜索锚定到行的开头。