4

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.

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

1 Comment

Ty Never thought of using Look Behind functionality of Regex.
1

Check if this works

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

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

Comments

0

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

1 Comment

I want a solution for parsing a generic insert query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.