Can I use regex to parse a word out of a phrase?

I am trying to parse table names from a list of insert statements, all of which are of the form insert into table_a. For that statement, I would like to find the name table_a.

My current code to do this is pretty clunky, could this be accomplished with regex?

    int index = query.indexOf("insert into");
    if (index >= 0) {
        query = query.substring(index + "insert into".length());
        query = query.trim();

        index = query.indexOf(" ");
        if (index >= 0)
            return query.substring(0, index);
        else
            return query; // tablename is last word in query
    }

1 answer

  • answered 2018-02-13 01:59 Tim Biegeleisen

    Yes, regular expressions should help here:

    String input = "INSERT INTO tableA ... INSERT INTO tableB";
    String pattern = "insert into ([\\s]+)";
    List<String> tables = new ArrayList<>();
    
    Pattern r = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
    
    Matcher m = r.matcher(input);
    while (m.find()) {
        tables.add(m.group(1));
        System.out.println(m.group(1));
    }
    
    tableA
    tableB
    

    Demo

    Note that I assume your table names don't have spaces. If they do, then a better approach would be to match up until the opening parenthesis, assuming your insert statements are standard SQL.