Reputation: 23
I am using VB.NET to write a winforms application, how can I use regular expression to remove spaces between "[" and "]" in a string?
For example, for a string
"[Product Name] Like '%Dragon Ball%' AND [Product Type] Like '%Toy%'"
I want the result to be
"[ProductName] Like '%Dragon Ball%' AND [ProductType] Like '%Toy%'"
I tried this, but it is not working:
Public Function RemoveSpaceInFieldNames(ByVal expression As String) As String
Dim regex As RegularExpressions.Regex = New
RegularExpressions.Regex(String.Format("\{0}\s*\{1}", "[", "]"))
Return regex.Replace(expression, String.Empty)
End Function
Upvotes: 2
Views: 437
Reputation: 23
Thank you so much ctwheels! Your answer works perfectly!!!
Public Function RemoveSpaceInFieldNames(ByVal expression As String) As String
Dim regex As RegularExpressions.Regex = New RegularExpressions.Regex("(?<=\[[^]]*)\s")
Return regex.Replace(expression, String.Empty)
End Function
Upvotes: 0
Reputation: 22817
(?<=\[[^]]*)\s
(?<=\[[^]]*)
Positive lookbehind ensuring the following matches
\[
Match [
literally[^]]*
Match any character except ]
any number of times\s
Match any whitespace characterYou can append (?=[^[]*])
if you want to ensure there's a ]
sometime afterwards as well, but, based on your sample, I don't think this is necessary.
Alternatively, you can also use \s(?=[^[]*])
with the Right to Left
modifier as this link shows.
Replace with an empty string.
Result: [ProductName] Like '%Dragon Ball%' AND [ProductType] Like '%Toy%'
Upvotes: 6