Dwight
Dwight

Reputation: 93

VB.Net Regex replace double quote inside of brackets

I have been spinning my wheels trying to figure this out. I need to replace double quotes inside a set of brackets. My example below shows single quotes but I am still having issues

This works for me -

Dim input As String = "This is my ['Test'] that works"
Dim output As String = Regex.Replace(input, "(?<=my.*)'(?=.*that)", "?")

Produces this string - This is my [?Test?] that works.

But if I try this is appends instead of replacing the single quote -

Dim input As String = "This is my ['Test'] that works"
Dim output As String = Regex.Replace(input, "(?<=[.*)'(?=.*])", "?")

Produces this which is not what I want - This is my ['?Test'?] that works.

As you can see the Regex.replace is appending the ? after the single quote, but I need it to replace the single quote with the ?. I am stumped.

Upvotes: 2

Views: 1788

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626804

To match all single quotes inside square brackets, you need to escape the opening [ or it will be treated as a special character (opening a character class):

(?<=\[[^][]*)'(?=[^][]*])

Also, you need to restrict the characters to be different from [ and ]. For that, you can use a [^][] negated character class (this will match any character other than [ and ]).

See regex demo

enter image description here

Upvotes: 1

Related Questions