代码之家  ›  专栏  ›  技术社区  ›  Matt Plank

方括号内字符的正则表达式[重复]

  •  2
  • Matt Plank  · 技术社区  · 12 年前

    我正在PowerShell中创建一个正则表达式。这是VS2012的一个postbuild事件的开始,该事件用于转换sql,以便我的表名和列名中没有任何空格。一旦成功,我就可以修改一个脚本,用正则表达式字符串替换文件的内容。我一直在和 this tutorial ,但当空格位于开方括号和闭方括号之间时,我似乎无法将空格替换为下划线。

    以下是我想如何转换sql的示例:

    转换:

    select * from [Existing product] where [Existing product].[Desc value] = 26
    

    收件人:

    select * from [Existing_product] where [Existing_product].[Desc_value] = 26
    

    当我在powershell ISE中运行此脚本时:

    #Example of PowerShell Regex Replace
    $newline = '
    '
    $strText = 'select * from [Existing product] where [Existing product].[Desc value] = 26'
    $Pattern = '(?<=\[)(\s(?<=\s))(?=\])'
    $New = "_"
    $newline
    'SourceText: '
    $strText
    $newline
    $strReplace = [regex]::replace($strText, $pattern, "$New")
    "We will now replace $Pattern with $New :" 
    $newline
    $strReplace
    

    我得到这样的结果:

    PS C:\> C:\REGEX.ps1
    
    SourceText: 
    select * from [Existing product] where [Existing product].[Description value] = 26
    
    
    We will now replace (?<=\[)(\s(?<=\s))(?=\]) with _ :
    
    
    select * from [Existing product] where [Existing product].[Description value] = 26
    

    我希望看到上面用下划线替换空格的字符串。

    我的正则表达式当前为 (?<=\[)(\s(?<=\s))(?=\]) 但显然它只选择方括号紧挨着的空格。上面的正则表达式缺少什么?

    如果你有任何问题,请告诉我,谢谢你的帮助!

    2 回复  |  直到 12 年前
        1
  •  2
  •   Has QUIT--Anony-Mousse    12 年前

    是的,除非添加填充,否则它只会选择完全匹配的项。

    大概 (?<=\[.*?)(\s(?<=\s))(?=.*?\]) 已经帮你搞定了。但总的来说,您的regexp似乎A)过于复杂,B)regexp不是这项工作的合适工具。

    我认为正则表达式一般不会起作用。像这样的绳子怎么样:

    [a] [b]
    

    我相信这会变成

    [a]_[b]
    

    大概 (?<=\[[^\]]*?)(\s(?<=\s))(?=[^\[]*?\]) 行得通,也许不行——不管怎样,都是一团糟!

    你真的应该考虑把所有的 \[([^\]]*)\] 分组,然后用第二步重写这些。

    SQL可能是 不是常规语言 ,但上下文无关。(参见乔姆斯基层次结构)

        2
  •  2
  •   mjolinor    12 年前

    这似乎奏效了:

    $string = 'select * from [Existing product] where [Existing product].[Desc value] = 26'
    
    $string -replace '(\[\S+)\s(\S+\])','$1_$2'
    

    从[Existing_product]中选择*,其中[Existining_product]。[描述值]=26

    如果有多个嵌入式空间,情况会变得更加复杂。

     $string = 'select * from [Existing product one] where [Existing product one].[Desc value] = 26'
    
    [regex]$regex = '(\[[^\]]*\])'
    
    $regex.Matches($string) | 
    %{$string = $string -replace [regex]::escape($_.value),($_.value.replace(' ','_'))}
    $string
    

    从[Existing_product_one]中选择*,其中[Existining_product_one]。[描述值]=26