views:

28

answers:

1

I have some inherited legacy language code snippets stored in a database table that I need to transform to a SQL like syntax so it can be used more effectively.

For example, one of the snippets is of the form

keyword = [a,b,c,x:y,d,e,f,p:q]

to indicate either discrete comma separate values or a range of colon-delimited values

How can I transform this to the equivalent SQL friendly snippet which would be

keyword in (a,b,c) or keyword between x and y or keyword in (d,e,f) or keyword between p and q

Thanks

A: 

It isn't regex but the first this that comes to mind it extracting the text within the square brackets so you have

textVariable  = a,b,c,x:y,d,e,f,p:q

then split with the columns so you have an array where each element is part of the string. So your resulting array would be

array[0] = a
...
array[3] = x:y
...

Then go through your array and create the final string you want. something like this (though it isn't tested)

finalString = ""
tempString = ""
for (int i = 0, i < array.length; i++) {
   if (array[i].contains(":")) { // then it needs to be between the two values
      if (finalString.length > 0) {
         finalString = finalString + " or "; // need to add an 'or'
      }
      if (tempString.length > 0) { // then need to add the keyword in (...) to finalString
         finalString = finalString + tempString + ") or ";
      }
      temparray = array[i].split(":")
      finalString = finalString + " keyword between " + temparray[0] + " and " + temparray[1]
   } else {
      if (tempString.length = 0) {
         tempString= "keyword in ("; // need to start the next set
      } else {
         tempString = tempString + ", "
      }
      tempString = tempString + array[i];
   }
} 
Kyra
I was hoping using regular expressions would lead to a more succinct solution rather than boring old string parsing. :-) The keyword and each value/range of values could be captured in a sub-expression and the replacement string could replay the expression using either IN or BETWEEN depending on whether the captured value has/doesn't have a colon.Thanks :-)
VANJ
No problem.. It was just want I thought up first. Figured it would be better than nothing. :)
Kyra