【发布时间】:2017-05-13 19:59:40
【问题描述】:
我有一个类似这样的 SQL 脚本:
DECLARE @MyVariable1 = 1
DECLARE @MyVariable1 = 10
DECLARE @MyVariable3 = 15
DECLARE @MyVariable2 = 20
DECLARE @MyVariable1 = 7
DECLARE @MyVariable2 = 4
DECLARE @MyVariable4 = 7
DECLARE @MyVariable2 = 4
当然,真正的脚本中间还有很多其他的东西,但我想写一个给定上述输入的函数,输出如下:
DECLARE @MyVariable1 = 1
@MyVariable1 = 10
DECLARE @MyVariable3 = 15
DECLARE @MyVariable2 = 20
@MyVariable1 = 7
@MyVariable2 = 4
DECLARE @MyVariable4 = 7
@MyVariable2 = 4
基本上删除了已声明变量的重复 DECLARE 语句
我目前的解决方案是这样的:
Private Function RemoveDuplicateDeclarations(commandText As String) As String
Dim lines = commandText.Split(New String() { vbCrLf }, StringSplitOptions.RemoveEmptyEntries)
Dim declarationRegex As New Regex("(\r|\n|\r\n) *DECLARE *(?<initialization>(?<varname>[^ ]*) *.*)" & vbCrLf , RegexOptions.Multiline Or RegexOptions.IgnoreCase)
Dim declaredVariables As New List(Of String)
Dim resultBuilder As New StringBuilder()
For Each line In lines
Dim matches = declarationRegex.Matches(line)
If matches.Count > 0 Then
Dim varname = matches(0).Groups("varname").Value
If declaredVariables.Contains(varname) Then
resultBuilder.AppendLine(declarationRegex.Replace(line, "${initialization}"))
Else
declaredVariables.Add(varname)
resultBuilder.AppendLine(line)
End If
Else
resultBuilder.AppendLine(line)
End If
Next
Return resultBuilder.ToString()
End Function
它非常适合我的脚本(并且不会有任何新脚本),但它似乎有点过于复杂,因为我可以匹配我想要替换的内容我想知道是否有办法只需使用一些参数运行Regex.Replace() 并在一行中完成它
欢迎使用 C# 解决方案
-编辑-
为了澄清我想要实现的目标,我想要以下格式的答案,或者解释这是不可能的(允许修改正则表达式)。
Private Function RemoveDuplicateDeclarations(commandText As String) As String
Dim regex As New Regex("(\r|\n|\r\n) *DECLARE *(?<initialization>(?<varname>[^ ]*) *.*)" & vbCrLf , RegexOptions.Multiline Or RegexOptions.IgnoreCase)
Return regex.Replace(commandText, "What do I put here???????")
End Function
【问题讨论】:
-
您使用 C# 和 VB.NET 标记了您的问题,但您的代码在 VB.NET 中。是不是意味着C#标签可以去掉?
-
可以,我标记了 c#,因为我不介意是否有人想在 c# 中回答,因为正则表达式在两种环境中的工作方式相同