Regex for SQL insert query

2.3k views Asked by At

I am trying to get the regex for SQL insert query. I need to extract the table name from the query. What should be the regex for this ? I am using Java

I looked at this link but unable to get the table name. Regular expression to extract SQL query

2

There are 2 answers

0
AudioBubble On

For that type of query

INSERT INTO 
    table_name 
  VALUES 
    (value1,'value which contains semicolon ;;;;',value3,...);

public static String regex = "(?i)insert into//s+(//S+)//s+"

    public static void printMatches(String text, String regex) {
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(text);
      // Check all occurrences
      while (matcher.find()) {
        System.out.println(" Found: " + matcher.group().replaceAll("(?i)insert into", "");
      }
    }
0
craftsmannadeem On

Regular Expressions are not full proof solution for extracting table names from SQL queries... As tons of things has to be considered, which would be trickier to express in RegX, and would break out in one or other cases....

You can use the following, ultra light, ultra fast library to do that in an elegant way

<dependency>
  <groupId>com.github.mnadeem</groupId>
  <artifactId>sql-table-name-parser</artifactId>
  <version>0.0.1</version>

and Execute the following query

 new TableNameParser(sql).tables()

For more details refer the project

Disclaimer: I am the owner of the library