【问题标题】:Change syntax using regular expression使用正则表达式更改语法
【发布时间】:2010-08-04 15:23:12
【问题描述】:

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

例如,其中一个 sn-ps 的格式为

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

表示离散的逗号分隔值或冒号分隔值的范围

如何将其转换为等效的 SQL 友好 sn-p

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

谢谢

【问题讨论】:

  • 如果您希望在单个正则表达式替换中做到这一点:您很可能不能,因为对于大多数工具/语言,您只能用单个替换字符串替换模式。您不能“说”用replacementA 替换patternA,而是用replacementB 替换patternB。那么,您将使用什么工具来进行这些替换?

标签: sql regex pattern-matching


【解决方案1】:

这不是正则表达式,而是首先想到的是它提取方括号内的文本,所以你有

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];
   }
} 

【讨论】:

  • 我希望使用正则表达式会带来更简洁的解决方案,而不是无聊的旧字符串解析。 :-) 关键字和每个值/值范围可以在子表达式中捕获,替换字符串可以使用 IN 或 BETWEEN 重播表达式,具体取决于捕获的值是否有/没有冒号。谢谢:-)
  • 没问题.. 只是想让我先想到。觉得有总比没有好。 :)
  • 我有时认为人们对正则表达式的了解越少,他们认为它可以为他们做的事情就越多! :)
猜你喜欢
  • 2010-10-27
  • 2011-06-11
  • 2011-03-22
  • 2011-08-23
  • 2012-05-06
  • 2010-09-20
  • 2011-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多