2

I have a Lua editor in which I implemented syntax highlighting. I use regexes to match expressions like strings, comments, tokens, numbers, etc of Lua. The whole thing is made in Java and uses Java regexes. I had trouble with two things:

Multiline strings - Lua multiline brackets start and end with double square brackets [[ Everything between is the string, there can even be nested multiline strings. You can see what I made here, the regex is \[\[((?>[^\[\[\]\]]|(?R))*\]\]) and it works. It's similar to what you can see on this page under the match balanced constructs section. It finds expressions with equal amounts of [[ and ]] The thing is, recursion is not supported by Java regex engine. How can I replace it with something supported?

Multiline comments - Lua multiline comments start with --[====[ and end with ]====]. It ends only if there is as much equal signs as the opening bracket. There can be anywhere between 0 and infinite equal signs. I made this regex --\[\[((.|\n)*?)\]\] but it only works for the --[[ comment ]] pattern and do not support this --[==[ comment ]==]. Maybe I could do something like counting number of matches of equal signs at the opening then match the same the number for the closing tag. Is this possible in java regex? How?

1 Answer 1

4

Try this

--\[(=*)\[(.|\n)*?\]\1\]

Multiline string literals are absolutely the same but without leading --:

\[((=*)\[(.|\n)*?)\]\2\]
Sign up to request clarification or add additional context in comments.

4 Comments

Multiline strings in Lua cannot be nested: x = [[ [[ ]] ]] is syntax error
A note on (.|\n)*?: if the regex flavor is Java, avoid this construct, use .*? and just add (?s) at the beginning of the regex to avoid stackoverflow issue. Basically, always avoid (.|\n) thing.
@WiktorStribiżew Do you mean using single line flag so . also matches newline? Can you give example with the two regexes above?
1) (?s)--\[(=*)\[(.*?)\]\1\], 2) (?s)\[(=*)\[(.*?)\]\1\]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.