2

I need to find if a string start with 0 or more spaces followed by a comment string I don't know in advance, so I though of just constructing the pattern:

local pattern = "^(%s" .. comment_string .. ")"
if str:find(pattern) then
-- ...

The problem is that comment_string contains metacharacters most of the time (i.e. for lua I get "--" but I need "%-%-" for the pattern to work). I tried a bunch of things but I can't find a way to make it work. Any idea?

Ludo
  • 21
  • 3
  • See https://stackoverflow.com/a/6706023/107090 – lhf Jan 17 '22 at 17:48
  • magic characters are escaped using %. so just prepend `%` to each magic character in `comment_string` using [string.gsub](http://www.lua.org/manual/5.4/manual.html#pdf-string.gsub) – Piglet Jan 17 '22 at 18:36

1 Answers1

-1
local str = "--test"
local pattern = "^%-%-%s*(.*)$"
local _, _, contents = str:find(pattern)
print(contents)
noobyy
  • 123
  • 9
  • I get that, but the given string can begin with "--", "#!", "//", ";;" ", */", "'", etc. I don't know in advance which comment string I will have. I could try to find all the possibilities, put them in a table and make a pattern for each one but I though there were another simpler and less "heavy" way to achieve this. – Ludo Jan 17 '22 at 18:16
  • 1
    @Ludo - [less heavy way](https://pastebin.com/imNZFtK4) – Egor Skriptunoff Jan 19 '22 at 12:16