Question

I have a function which is used to replace some words with a few characters or numbers. I am using string.gsub() function in this way:

string.gsub(line, "[0-9%a%s/,-]+", "\t")

This works very good with strings with numbers, letters, spaces, ,, and /. I also would like to replace brackets like ( and ). But simply inserting () to my pattern doesn't work. I have also tried with %( and %) but it wasn't successful. How can I replace brackets in Lua using pattern in string.gsub() method?

Was it helpful?

Solution

The only characters that need to be escaped inside [] are []%-, all of which are escaped with %. As such, escaping - as follows works:

string.gsub(line, "[0-9%a%s/,%-()]+", "\t")

It's also probably worth mentioning that [0-9%a] is equivalent to [%d%a], which is equivalent to %w.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top