luastring-matching

Match start of line in multiline string in lua?


Let's say I want to match any sequence of the hash sign # at the start of a string; so I'd want to match ## here:

local mystr = "##First line\nSecond line\nThird line"

... and ### here:

local mystr = "First line\nSecond line\n### Third line"

... and nothing here:

local mystr = "First line\nSecond line\nThird line"

I guess, the pattern ^(%#+) could have worked here if the caret ^ meant start of a (multiline) line - however, as far as I can see, e.g. in How to match the start or end of a string with string.match in Lua?

^ at the start of a pattern anchors it to the start of the string. $ at the end of a pattern anchors it to the end of the string.

... the caret here would only match at the start of the multiline string (mystr) itself.

How could I go about matching a pattern that starts with "line start" in Lua?


Solution

  • You want to match either the start of the string ^ or after any newline \n character:

    mystr:match("^(%#+)") or mystr:match("\n(%#+)")
    

    I don't think you can combine it into one match. Logical 'or' in Lua patterns?