kshah
kshah

Reputation: 1847

Advanced Lua Pattern Matching

I would like to know if either/both of these two scenarios are possible in Lua:

I have a string that looks like such: some_value=averylongintegervalue

Say I know there are exactly 21 characters after the = sign in the string, is there a short way to replace the string averylongintegervalue with my own? (i.e. a simpler way than typing out: string.gsub("some_value=averylongintegervalue", "some_value=.....................", "some_value=anewintegervalue")

Say we edit the original string to look like such: some_value=averylongintegervalue&

Assuming we do not know how many characters is after the = sign, is there a way to replace the string in between the some_value= and the &?

I know this is an oddly specific question but I often find myself needing to perform similar tasks using regex and would like to know how it would be done in Lua using pattern-matching.

Upvotes: 2

Views: 358

Answers (1)

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

Yes, you can use something like the following (%1 refers to the first capture in the pattern, which in this case captures some_value=):

local str = ("some_value=averylongintegervalue"):gsub("(some_value=)[^&]+", "%1replaced")

This should assign some_value=replaced.

Do you know if it is also possible to replace every character between the = and & with a single character repeated (such as a * symbol repeated 21 times instead of a constant string like replaced)?

Yes, but you need to use a function:

local str = ("some_value=averylongintegervalue")
  :gsub("(some_value=)([^&]+)", function(a,b) return a..("#"):rep(#b) end)

This will assign some_value=#####################. If you need to limit this to just one replacement, then add ,1 as the last parameter to gsub (as Wiktor suggested in the comment).

Upvotes: 3

Related Questions