You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SSMS 2017中用正则匹配SQL脚本的最后方括号?

Fixing Regex to Replace Brackets with Quotes After AS in SSMS 2017

Got it, let's sort out this regex issue for your SQL script. Your goal is to target the final pair of square brackets immediately following AS in each clause, swapping those brackets for single quotes—here's how to do it right with PCRE-compatible regex (since you mentioned behavior matches PCRE PHP):

Correct Regex & Replacement Steps

First, open the Find/Replace dialog in SSMS 2017 (Ctrl+H), check the "Use regular expressions" box, then use these values:

  • Find what: (\s+AS\s+)\[(.*?)\]
  • Replace with: $1'$2'

Regex Breakdown

Let's break down why this works perfectly for your case:

  • (\s+AS\s+): Captures one or more whitespace characters, followed by AS, followed by one or more whitespace characters. This ensures we only target the AS clause we care about, ignoring brackets elsewhere in the query (like inside the ISNULL function).
  • \[(.*?)\]: Matches the opening bracket [, uses a non-greedy .*? to capture everything inside the brackets (stopping at the first closing ]—ideal since your brackets don't have nested content), then matches the closing ].

Example Result

Applying this to your sample script:

Original:
,ISNULL([Gt 01 To 02 Weeks SUM 1],0) AS [Gt 01 To 02 Weeks SUM] ,ISNULL([Gt 02 To 03 Weeks SUM 1],0) AS [Gt 02 To 03 Weeks SUM]

After replacement:
,ISNULL([Gt 01 To 02 Weeks SUM 1],0) AS 'Gt 01 To 02 Weeks SUM' ,ISNULL([Gt 02 To 03 Weeks SUM 1],0) AS 'Gt 02 To 03 Weeks SUM'

Why Your Previous Attempts Failed

  • Your first regex (?<=\sAS\s).*(\[)Gt|SUM(\]) used greedy .* which matched everything from AS to the end of the line, plus split grouping across alternations—this couldn't target the full bracket pair correctly.
  • Your second regex (?<=\sAS\s).*?(\[)|(?<=\sAS\s)?(\]) tried to match [ and ] separately, leading to extra matches (like the closing bracket from the ISNULL clause) because there was no logic to tie the opening and closing brackets together as a single pair after AS.

内容的提问来源于stack exchange,提问作者QHarr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:16:45