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
答案 0 :(得分:2)
请勿在正则表达式中使用贪心.*
。你可以使用这个正则表达式:
\bINSERT\s+INTO\s+\S+\s*\(([^)]+)\)\s*VALUES\s*\(([^)]+)\)
在Java中:
String regex = "\\bINSERT\\s+INTO\\s+\\S+\\s*\\(([^)]+)\\)\\s*VALUES\\s*\\(([^)]+)\\)";
这将给出:
Group 1: "column1, column2, column3, column4, column5 "
Group 2: "1, 'Hi', 'A,B', '', null"
答案 1 :(得分:1)
试试这个
"INSERT INTO.*\\((.*)\\).*VALUES.*\\((.*)\\)"
你所犯的错误并没有逃避括号。没有逃脱\(正则表达式假设你正在开始一个小组。