0

I'm searching for all SELECT * like queries in my code base to replace it with the actual name of the columns.

I'm trying to build a regex that can find if a '*' is found between the word SELECT and FROM.

This should match the following patterns :

   #1 SELECT * FROM tablename
   #2 SELECT tablename.* FROM tablename
   #3 SELECT tb1.col1, tb2.* FROM table tb1, table2 tb2

But not this one :

 #4 SELECT col FROM table

My attempts so far (in the search box of PhpStorm):

SELECT *

Output: 1, 2, 3 and 4

I also tried the answer from Regex Match all characters between two strings

(?<=SELECT)(.*)(?=FROM)

Output: 1, 2, 3 and 4

I went further in StackOverflow and found this one:

SELECT\s+?[^\s]+?\s+?FROM\s+?[^\s]+?\s+?WHERE.

Output: 1, 2, 3 and 4

Can you help me please ?

jarlh
  • 42,561
  • 8
  • 45
  • 63
E.Fritschy
  • 33
  • 5
  • Search from where? – jarlh Sep 19 '18 at 09:06
  • 1
    How did you try? Share your regex attempts along with current output – Andersson Sep 19 '18 at 09:08
  • I will use grep to search in my entire codebase (php) – E.Fritschy Sep 19 '18 at 09:08
  • 1
    Hey why is my question down voted ? I'm quite sure this hasn't asked exactly the same way. I understand it might be not well formulated. I apologize, it's my first question here. Can you help me to formulate it better so it can be clearer and more useful to other people ? – E.Fritschy Sep 19 '18 at 09:27

1 Answers1

1

The problem you are encountering is that * in regex language is a meta character which means that it has a special meaning like .+?[]{}()^$\ to retreive their literal meaning they should be preceded with a \ or between squared brackets. So to match a * the regex can be \*. Following regex uses an atomic group and a lookahead assertion to ensure there is no SELECT or FROM word between SELECT and *

SELECT(?>(?!SELECT|FROM).)*\*
Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36