1

Been stuck on this for over a day.

I'm trying to use gsub to extract a portion of an input string. The exact pattern of the input varies in different cases, so I'm trying to use a variable to represent that pattern, so that the same routine - which is otherwise identical - can be used in all cases, rather than separately coding each.

So, I have something along the lines of:

newstring , n = oldstring:gsub(matchstring[i],"%1");

where matchstring[] is an indexed table of the different possible pattern matches, set up so that "%1" will match the target sequence in each matchstring[].

For instance, matchstring[1] might be

"\[User\] <code:%w*>([^<]*)<\\code>.*"  -- extract user name from within the <code>...<\code>

while matchstring[2] could be

"\[World\] (%w)* .*" -- extract user name as first word after prefix '[World] '

and matchstring[3] could be

"<code:%w*>([^<]*)<\\code>.*"  -- extract username from within <code>...<\code> at start

This does not work.

Yet when, debugging one of the cases, I replace matchstring[i] with the exact same string -- only now passed as a string literal rather than saved in a variable -- it works.

So.. I'm guessing there must be some 'processing' of the string - stripping out special characters or something - when it's sent as a variable rather than a string literal ... but for the life of me I can't figure out how to adjust the matchstring[] entries to compensate!

Help much appreciated...

Ivandar
  • 11
  • 1
  • you should always provide example input with such a question, not just the pattern. also the code you use to create the pattern table. just in case you're doing something wrong there. ideally provide a [mcve] we can just copy paste and run – Piglet Feb 23 '21 at 16:32
  • 1
    your examples contain invalid escape sequences btw. `\[` is not ok. use `%` to escape magic characters – Piglet Feb 23 '21 at 16:42

1 Answers1

0

FACEPALM

Thankyou, Piglet, you got me on the right track.

Given how this particular platform processes & passes strings, anything within <...> needed the escape character \ for downstream use, but of course - duh - for the lua gsub's processing itself it needed the standard %

much obliged

Ivandar
  • 11
  • 1