WhimsicalGamez
WhimsicalGamez

Reputation: 31

How to use gsub with special characters

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"

Upvotes: 2

Views: 522

Answers (2)

Doyousketch2
Doyousketch2

Reputation: 2147

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 )

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626926

%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.

Upvotes: 2

Related Questions