简体   繁体   English

正则表达式使用 match() 提取 javascript 中的字符串数组

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

I'm trying to use string.match() to extract column names from an SQL query.我正在尝试使用string.match()从 SQL 查询中提取列名。

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我试过的: /(?<.\()(\")?+?(\")(?!\ \()/g

Is there a way to get column names without double quotes?有没有办法在没有双引号的情况下获取列名?

This regex will match " when its it not followed or preceded by ) or (此正则表达式将匹配"当它后面没有或前面没有)(

regex101 demo正则表达式101演示

(?<![\)\(])"(?![\)\(])

then you can substitute it with nothing' so they will be removed那么你可以用任何东西代替它'所以它们将被删除

You were close.你很亲密。 Use the regex, /(?<?\()(:.\")(?+?)(:?\")(?!\s*\()/gm for your requirement.使用正则表达式/(?<?\()(:.\")(?+?)(:?\")(?!\s*\()/gm满足您的要求。

Check this for the demo and the explanation of the regex.检查演示和正则表达式的解释。

Demo using Java:使用 Java 的演示:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        // Test string
        String str="CREATE TABLE \"listings\" (\n" + 
                "        \"listing_id\"    INTEGER UNIQUE,\n" + 
                "        \"state\" TEXT,\n" + 
                "        \"title\" TEXT,\n" + 
                "        \"description\"   TEXT,\n" + 
                "        \"price\" TEXT,\n" + 
                "        \"currency_code\" TEXT,\n" + 
                "        \"url\"   TEXT,\n" + 
                "        PRIMARY KEY(\"listing_id\")";
        
        Pattern pattern = Pattern.compile("(?<!\\()(?:\\\")(.+?)(?:\\\")(?!\\s*\\()");
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}

Output: Output:

listing_id
state
title
description
price
currency_code
url

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM