user990967
user990967

Reputation: 444

Parsing Insert SQL Query in Java using Regular Expression

I want to parse the Insert Query in Java using Regex.

Following is the sample string


    INSERT INTO table_name (c1,c2,c3) VALUES (abc,def,ghi) , (jkl,mno,pqr)

I want the following output:

Group1: table_name  
Group2: c1,c2,c3    
Group3: abc,def,ghi
Group4: jkl,mno,pqr

I have tried the following regular Expression:


    INSERT INTO ([A-Za-z][A-Za-z0-9_-]*) (?:\((.*)\))?\s*VALUES (\((,)?(.*)\))*

The output is

Group1 : table_name
Group2 : c1,c2,c3
Group3 : (abc,def,ghi) , (jkl,mno,pqr)
Group4 : Empty
Group5 : abc,def,ghi) , (jkl,mno,pqr

Please help me how to get the desired result.

Upvotes: 4

Views: 5972

Answers (3)

Mahesh Revaskar
Mahesh Revaskar

Reputation: 104

Check if this works

(INSERT INTO) (\S+).*\((.*?)\).*(VALUES).*\((.*?)\)(.*\;?)

https://regex101.com/r/0wsoqJ/4

Upvotes: 1

Cà phê đen
Cà phê đen

Reputation: 1953

You can try this regex:

((?<=(INSERT\\sINTO\\s))[\\w\\d_]+(?=\\s+))|((?<=\\()(\\s*[\\w\\d_,]+\\s*)+(?=\\)))

Explanation:

(?<=(INSERT\\sINTO\\s))[\\w\\d_]+(?=\\s+) matches [\\w\\d_]+ between (INSERT\\sINTO\\s) and \\s+

(?<=\\()(\\s*[\\w\\d_,]+\\s*)+(?=\\)) matches [\\w\\d_,]+ between \\( and \\)

Here is an example code:

import java.util.regex.*;

public class HelloWorld {
    public static void main(String []args){
        String test = "INSERT INTO table_name (c1,c2,c3) VALUES (abc,def,ghi) , (jkl,mno,pqr)";

        String regex = "((?<=(INSERT\\sINTO\\s))[\\w\\d_]+(?=\\s+))|((?<=\\()([\\w\\d_,]+)+(?=\\)))";

        Pattern re = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

        Matcher m = re.matcher(test);
        while (m.find()) {
            System.out.println(m.group(0));
        }
     }
}

The output is like:

table_name
c1,c2,c3
abc,def,ghi
jkl,mno,pqr

Upvotes: 7

jj27
jj27

Reputation: 178

For this specific example of your query, the following regex should do the trick.

INSERT INTO (\S+) \((\S+)\) VALUES \((\S+)\) , \((\S+)\)

https://regex101.com/r/2Kdayp/1

Upvotes: 0

Related Questions