Remove Non Printable Characters

I need to remove non printable characters from various textarea’s. Most importantly, linefeed and carriage returns.

I suck at regex! I do have one to replace any non alpha numeric characters. What would I use in the code below for a search pattern to just remove control codes?

Dim reg as new RegEx
reg.searchPattern = "[^a-zA-Z0-9]"
reg.replacementPattern = ""
reg.Options.ReplaceAllMatches = True

Dim source as string = item
Dim result as string = reg.replace( source )


Return result

Thanks!

 "[^\x20-\x7E]" 

matches any non-printable character, including control codes like linefeed (\n), carriage return (\r), and other non-printable ASCII characters.

If you want to be even more specific and only remove the control characters (ASCII 0-31) and keep the printable ones, you can use this pattern instead:

 reg.searchPattern = "[\x00-\x1F]"
1 Like

Thanks for the assist!

A due diligence question: are you only looking to remove characters that are not A-Z a-z etc? What about Ä, ñ, etc?

cr and lf characters were what I was removing. Anything ascii 0 to 31 made more sense though.