Reputation: 7899
In java I am trying to extract column names and their values using Regex
and Matcher
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: " + m.group(0));
System.out.println("Found value: " + m.group(1));
System.out.println("Found value: " + m.group(2));
} else {
System.out.println("NO MATCH");
}
Expectation:
Group-1 = column1, column2, column3, column4, column5
Group-2 = 1, 'Hi', 'A,B', '', null
Upvotes: 1
Views: 1260
Reputation: 1413
Try this
"INSERT INTO.*\\((.*)\\).*VALUES.*\\((.*)\\)"
The mistake you were doing is not escaping the brackets. Without the escaping \( Regex assumes you are starting a group.
Upvotes: 1
Reputation: 785256
Don't use greedy .*
in your regex. You can use this regex:
\bINSERT\s+INTO\s+\S+\s*\(([^)]+)\)\s*VALUES\s*\(([^)]+)\)
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"
Upvotes: 2