使用正则表达式更改语法

问题描述 投票:0回答:1

我有一些继承的遗留语言代码片段存储在数据库表中,我需要将它们转换为类似 SQL 的语法,以便更有效地使用它。

例如,其中一个片段的形式为

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

指示离散的逗号分隔值或一系列冒号分隔的值

如何将其转换为等效的 SQL 友好片段

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

谢谢

sql regex
1个回答
0
投票

这不是正则表达式,而是第一个想到的它提取方括号内的文本,这样你就有了

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

然后按列进行拆分,这样您就得到了一个数组,其中每个元素都是字符串的一部分。所以你得到的数组将是

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

然后遍历数组并创建所需的最终字符串。像这样的东西(虽然没有经过测试)

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];
   }
} 
© www.soinside.com 2019 - 2024. All rights reserved.