Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace brackets in Lua using string.gsub?

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?

like image 491
woyaru Avatar asked Apr 15 '26 18:04

woyaru


1 Answers

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.

like image 66
furq Avatar answered Apr 19 '26 23:04

furq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!