0

I want to remove some characters from a textbox. It works, but when i try to replace the "[" character it gives a error. Why?

    Return Regex.Replace(html, "[", "").Replace(",", " ").Replace("]", "").Replace(Chr(34), " ")

error

When i delete the "[", "").Replace( part it works great?

Return Regex.Replace(html, ",", " ").Replace("]", "").Replace(Chr(34), " ")
3
  • Try this Return Regex.Replace(html, "\[", "").Replace(",", " ").Replace("]", "").Replace(Chr(34), " ") Commented Feb 2, 2017 at 19:43
  • 2
    @SteelToe would be nice to explain why : because [ has special meaning in a regex it must be escaped with a backslash when literally searching for it. Commented Feb 2, 2017 at 19:45
  • @SteelToe Thanks for posting the correct code! It's working now. Thanks Aybe for explaining! Interessting. I found more info at javascriptkit.com. Thanks again :) Commented Feb 2, 2017 at 19:51

2 Answers 2

2

The problem is that since the [ character has a special meaning in regex, It must be escaped in order to use it as part of a regex sequence, therefore to escape it all you have to do is add a \ before the character.

Therefore this would be your proper regex code Return Regex.Replace(html, "\[", "").Replace(",", " ").Replace("]", "").Replace(Chr(34), " ")

Sign up to request clarification or add additional context in comments.

Comments

1

Because [ is a reserved character that regex patterns use. You should always escape your search patterns using Regex.Escape(). This will find all reserved characters and escape them with a backslash.

Dim searchPattern = Regex.Escape("[")
Return Regex.Replace(html, searchPattern, ""). 'etc...

But why do you need to use regex anyway? Here's a better way of doing it, I think, using StringBuilder:

Dim sb = New StringBuilder(html) _
.Replace("[", "") _
.Replace(",", " ") _
.Replace("]", "") _
.Replace(Chr(34), " ")
Return sb.ToString()

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.