Lua | String Patterns | Pattern to find strings within a string

Viewed 353

I am making an in-game script editor, and its almost complete. Aside from needing to script in key-binds and such, I need to fix some problems with the Syntax Highlighter. Here is how the editor looks so far:
(UI has had no work done to it, ignore it.)

Picture of editor in game

As you can clearly see, there are some bugs to work out, such as some parenthesis refusing to highlight. The bigger problem resides in my pattern for findings strings though:
(([^\\]*["\']).*%2)
This pattern causes this:
Items between two strings become highlighted
I took a break from working on this a few weeks ago, and I don't really remember as well on how patterns work. I have tried modifying my existing pattern to prevent text between strings from being included with match, but it either selects EVERYTHING, or doesn't find any strings.
I need to make sure it doesn't find \' or \" to be an indicator for a string either.

2 Answers

Your pattern is a bit complicated. You can simply match balanced pairs of " using the pattern %b""

local myString = 'local a = {"one", "two", "tree"}'

for str in myString:gmatch('%b""') do print(str) end

prints

"one"
"two"
"tree"

See https://www.lua.org/manual/5.3/manual.html#6.4.1

%bxy, where x and y are two distinct characters; such item matches strings that start with x, end with y, and where the x and y are balanced. This means that, if one reads the string from left to right, counting +1 for an x and -1 for a y, the ending y is the first y where the count reaches 0. For instance, the item %b() matches expressions with balanced parentheses.

Your issue is that you are using a greedy match. This will purposely find the longest matching string. Instead you should use a lazy match. This will allow you to match just the first string. Lazy matches use the - symbol instead of the +

So now you can write simple pattern for each variant of the string

> print(([["foo"]]):match("\"[^\"]-\""))
"foo"
> print(([["foo"  "bar"]]):match("\"[^\"]-\""))
"foo"
>
Related