skip to Main Content

I would like to have a regular expression that convert below string to the "where" clause in sql.

​For example:

/* Col1: ABC, Col2: 123, ColN: Bla bla... */

to:

WHERE Col1 = 'ABC' AND Col2 = '123' AND ColN = 'Bla Bla...'

If this is something that feasible?

2

Answers


  1. We could use a regex replacement here:

    var input = "/* Col1: ABC, Col2: 123, ColN: Bla bla... */";
    var output = input.replace(/^S+s*|s*S+$/g, "")
                      .replace(/([^:s]+):s*([^,]+)/g, "$1 = '$2'")
                      .replace(/s*,s*/g, " AND ");
    output = "WHERE " + output;
    console.log(output);
    Login or Signup to reply.
  2. You could use this regex:

    //*|,|s*([^:]+):s+(.*?)(?=,|s+*/)|s+*//g
    

    to match the individual components of the input: /*, ,, col: value and */ and replace them with the appropriate values: WHERE, AND, col = 'value' and '' using a replacer function:

    data = '/* Col1: ABC, Col2: 123, ColN: Bla bla... */'
    
    result = data.replace(//*|,|s*([^:]+):s+(.*?)(?=,|s+*/)|s+*//g,
      (m, p1, p2) => {
        if (m == '/*')
          return 'WHERE '
        else if (m.endsWith('*/'))
          return ''
        else if (m == ',')
          return ' AND '
        else
          return `${p1} = '${p2}'`
      }
    )
    
    console.log(result)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search