Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How does gsub work exactly?

Asked by 8 years ago

I've read the wiki article on gsub, and I dont completely understand how it works. I get that it replaces certain things in a string, can fund patterns, etc, but that's about it. Can I use gsub to replace individual letters & numbers within a string with other letters & numbers? Any help is appreciated, thanks! :)

1 answer

Log in to vote
5
Answered by 8 years ago
Edited 7 years ago

gsub stands for global substitution

function gsub(string, match, sub) -> newString
Every time it finds a part of the string matching a pattern at match and replaces it with sub. There are a few special cases for using gsub:

If sub is a function

The capture is passed as an argument to sub. If there are multiple captures in the match string, then they are passed as a tuple of arguments. The function return will be substituted into the string.

If sub is a table

The whole string is replaced with the value for the key matching the first capture. It's a little bit difficult to explain in words, but I got you an example so it's fine.

str = "Hello World";
print (
    str:gsub (
        "%S+", -- Anything not a space
        {Hello = "Good morning"} -- Replace "Hello" with "Good morning"
    )
) --> Good morning World

print (
    str:gsub (
        "(.)%S+", -- Anything, followed by anything not a space
        {Hello = "Hi", H = "E"} -- Replace "Hello" with "Hi" and "H" with "E"
    )
) --> E World

If you're confused about that second one, let me explain. It first captures "(H)ello", where "H" becomes the capture. It passes "H" to the table, and finds "E". It replaces "Hello" with "E". It then finds "( )World", checks " " in the table, and doesn't replace anything because it finds no " " key in the table, leaving " World" as-is.

If you're using captures

If you are using captures in match then you can place the capture back into the string at sub using %n where n is the number position of the capture. Good luck if you have more than 9 captures.

0
Thanks! This is really helpful! :D AwsomeSpongebob 350 — 8y
Ad

Answer this question