I need help removing all special characters from a string except underscores

How would I take a string with special characters (Ex. “This_is a string!”) and turn it into "This_is a string”? I’m able to remove all special characters just fine using string.gsub(string, ‘%p’, ‘’) it’s just the underscore part that confuses me.

s = s:gsub("[^%w%s_]+", "")

This should anything that is not alphanumeric, not a space character, and anything that is not an underscore. The [] means a set, and the ^ is there to indicate that you want to match anything that is NOT what is inside the set

  • %w is the pattern for alphanumeric characters
  • %s is the pattern for whitespace
  • _ for underscores
16 Likes

Thank you! I was able to use your example to figure out what I needed to do!