Reputation: 35
I'm making a program that will correctly address the gender of the user. So it should replace every instance of he
to she
or vice versa.
The problem is this will also replace he
inside words such as them
, their
, help
...
This is where I'm stuck.
local str = "the he he's hell"
str = str:gsub("he", "she") --tried my best, not the correct solution!
print(str) --expecting "the she she's hell"
Basically replace all he
to she
.
Upvotes: 1
Views: 187
Reputation: 28950
One possible solution that works both ways:
str = str:gsub("%a+", {he = "she", she = "he"})
%a+
matches one or more letter which is basically word. that match is replaced by the respective table entry or stays unchanged.
There are other ways to to this but this is probably the shortest way to achieve a two-wway solution.
About the second param. I couldn't find any documentation about this. Do you have any?
Not sure where you've been looking for documentation but the Lua Manual says:
string.gsub (s, pattern, repl [, n])
...
If repl is a table, then the table is queried for every match, using the first capture as the key.
Upvotes: 2