I'm trying to use string.match()
to extract column names from an SQL query.
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
Is there a way to get column names without double quotes?
This regex will match "
when its it not followed or preceded by )
or (
(?<![\)\(])"(?![\)\(])
then you can substitute it with nothing' so they will be removed
You were close. Use the regex, /(?<?\()(:.\")(?+?)(:?\")(?!\s*\()/gm
for your requirement.
Check this for the demo and the explanation of the regex.
Demo using 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:
listing_id
state
title
description
price
currency_code
url
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.