如何在SSMS 2017中用正则匹配SQL脚本的最后方括号?
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 byAS, followed by one or more whitespace characters. This ensures we only target theASclause we care about, ignoring brackets elsewhere in the query (like inside theISNULLfunction).\[(.*?)\]: 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 fromASto 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 theISNULLclause) because there was no logic to tie the opening and closing brackets together as a single pair afterAS.
内容的提问来源于stack exchange,提问作者QHarr

