amicngh amicngh - 1 year ago 83
Java Question

Regex to extract column name and values not working

In java I am trying to extract column names and their values using

but dont know what I am doing wrong here.

String sql = "INSERT INTO MyTable (column1, column2, column3, column4, column5 ) VALUES (1, 'Hi', 'A,B', '', null)";
String pattern = "INSERT INTO.*((\\w)+).*\\((.*)\\).*VALUES.*\\((.*)\\)";

Pattern r = Pattern.compile(pattern);

Matcher m = r.matcher(sql);
if (m.find()) {
System.out.println("Found value: " +;
System.out.println("Found value: " +;
System.out.println("Found value: " +;
} else {
System.out.println("NO MATCH");


Group-1 = column1, column2, column3, column4, column5
Group-2 = 1, 'Hi', 'A,B', '', null

Answer Source

Don't use greedy .* in your regex. You can use this regex:


In Java:

String regex = "\\bINSERT\\s+INTO\\s+\\S+\\s*\\(([^)]+)\\)\\s*VALUES\\s*\\(([^)]+)\\)";

This will give:

Group 1: "column1, column2, column3, column4, column5 "
Group 2: "1, 'Hi', 'A,B', '', null"

RegEx Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download