How can I only replace one of multiple patterns from the string?

I’m not just trying to replace a specific pattern from the string. For example, let’s say the string is:

“The quick brown fox jumps over the lazy dog.”

As you can see the word “the” is in there twice. But instead of replacing both "the"s, I only want to replace one of them. How can I do that?

What regular expression are you currently using?

Replaces both the or The:

local s = "The quick brown fox jumps over the lazy dog"

s = string.gsub(s, "[Tt]he", "My")
print(s)

From the pil: Programming in Lua : 20.1
gsub has a fourth argument to limit the number of matches left to right.

local s = "The quick brown fox jumps over the lazy dog"

s = string.gsub(s, "[Tt]he", "My", 1)
print(s)
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.