How to use gsub with special characters

Viewed 159

it seems as if when I add a special character gsub no longer works for me.

how can I use text with such characters

 print(string.gsub("a !foo walking", "%a+",{
   ["!foo"] = "bar",
   }))

Desired output

"a bar walking"
2 Answers

%a matches letters only.

To match any non-whitespace characters, you can use %S:

print(string.gsub("a !foo walking", "%S+",{
   ["!foo"] = "bar",
}))

See an online Lua demo.

Version 1:

#! /usr/bin/env lua

text = 'a !foo walking'
subbed = string .gsub( text, '!foo', 'bar' )

print( subbed )

Version 2: same thing as before, just use : instead of . so your text becomes first arg in gsub() function

#! /usr/bin/env lua

text = 'a !foo walking'
subbed = text :gsub( '!foo', 'bar' )

print( subbed )
Related