SQL SELECT Statement in GO
Match the column list and table name from a SQL SELECT ... FROM statement.
Try it in the GO tester →Pattern
regexGO
SELECT\s+(.+?)\s+FROM\s+([\w."`\[\]]+) (flags: gis)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile("(?is)SELECT\\s+(.+?)\\s+FROM\\s+([\\w.\"`\\[\\]]+)")
input := `SELECT id, name FROM users`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
How the pattern works
SELECT\s+ matches the keyword and required whitespace. (.+?) lazily captures the column list. \s+FROM\s+ matches the FROM keyword. ([\w."`\[\]]+) captures the table identifier including dots (db.schema.table), and the three quoting styles SQL dialects use: "double", `backtick`, [bracket]. Flags: g (global), i (case-insensitive SELECT/FROM), s (dotAll so columns can span newlines).
Examples
Input
SELECT id, name FROM usersMatches
SELECT id, name FROM users
Input
select * from `orders`Matches
select * from `orders`
Input
INSERT INTO logsNo match
—