Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 881
sdbbs Avatar asked Oct 25 '25 14:10

sdbbs


1 Answers

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?

like image 171
Mikael Öhman Avatar answered Oct 27 '25 05:10

Mikael Öhman