Dynamic regex to capture

Not sure if this is actually possible, but consider the following text:

INSERT INTO cms_download_history
SET
user_id     = '{$userId}',
download_id     = '{$fileId}',
remote_addr     = '{$remote_addr}',
doa = GetDate()";

      

I want to change this like:

INSERT INTO cms_download_history
(user_id,download_id,remote_addr,doa)
VALUES('{$userId}','{$fileId}','{$remote_addr}',GetDate());

      

Doing a regex to find and replace this is easy as I know how many columns I have, but what if I am trying to do this for several similar queries without knowing the number of columns, i.e.

INSERT INTO mystery_table
SET
col1 = val1
col2 = val2
.... unknown number of columns and values.

      

Is there a dynamic regex I can write to detect this example?

+3


source to share


1 answer


In fact, if all queries look like this, with only a variable number of columns, you can get the field names with a simple, simple expression:

(\w+)\W*=\W*['"].+?(?!\\)['"],

      

Here's an example . Here's what it does:



  • It captures one or more characters of a word if:
    • Zero or more whitespace characters
    • Equal sign
    • Zero or more whitespace characters (again)
    • A '

      or "

      (start of line)
    • One or more characters
    • Optional '

      or"

    • Comma

Note that this assumes that all values โ€‹โ€‹are strings. If you also need room support please let me know.

+1


source







All Articles