简体   繁体   中英

Regex to capture multiple groups of SELECT queries in a single statement with 0 or more UNIONs?

I have a list of SQL queries which can range from a simple

SELECT * from ABC

to complex ones like

SELECT A,B,C from ABC Where Z=5 and T=10 UNION SELECT * from GHI Where i=100 UNION SELECT X,Y from XYZ

I would like to capture the bold sections using a regex. Currently, I have (SELECT[\\s]*.*from[\\s]*) but this treats the 2nd query as a single SELECT query ie SELECT .... from XYZ while I need it to find 3 parts highlighted above.

Can someone pls kindly offer some advice? Thanks.

The following pattern should work in pretty much any language in case-insensitive mode:

SELECT\s(?:(?!FROM)[\s\S])*\sFROM

This even works when the SQL code spreads across multiple lines.

Demo

Alternatively, enable single-line mode and just use a dot: SELECT\\s(?:(?!FROM).)*\\sFROM .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM