Jingobell
Jingobell

Reputation: 23

How to remove space between square brackets in vb.net?

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

Answers (2)

Jingobell
Jingobell

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

ctwheels
ctwheels

Reputation: 22817

See regex in use here

(?<=\[[^]]*)\s
  • (?<=\[[^]]*) Positive lookbehind ensuring the following matches
    • \[ Match [ literally
    • [^]]* Match any character except ] any number of times
  • \s Match any whitespace character

You 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

Related Questions