2

I am trying to perform a regex match in SQL Server Management Studio 2017 to then do a replace on part of a SQL script that looks as follows:

,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]

I want to match on the last [ and ] e.g. using example line [Gt 02 To 03 Weeks SUM]; so I can the replace [|] with '

I tried

(?<=\sAS\s).*(\[)Gt|SUM(\])

And this gives:

enter image description here

which is full matches rather than the group matches I wish to replace

I then tried:

(?<=\sAS\s).*?(\[)|(?<=\sAS\s)?(\])

But this matches one too many (i.e. it matches on the penultimate ] as well.

enter image description here

I tried a few other things to no avail.

Behaviour seems to match as per using PCRE PHP on regex 101. Example: here so I added that tag but I am not experienced enough in this domain to know if that is valid.

How do I change this regex please to only match on the last brackets?

1
  • 1
    Perhaps use 2 capturing groups with a replacement of $1'$2' for example (AS )\[([^\]]+)\] See regex101.com/r/8fmh11/1 Commented Oct 19, 2019 at 15:52

1 Answer 1

2

You might use 2 capturing groups and match the [ and ] so that they can be replaced with '

(AS )\[([^\]]+)\]
  • (AS ) Capture group 1 Match AS
  • \[ Match [
  • ( Capture group 2
    • [^\]]+ Negated character class, match any char 1+ times except ]
  • ) Close group
  • \] Match ]

Regex demo

In the replacement use the 2 capturing groups

$1'$2'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.