Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua regular expression with exactly one match

Tags:

regex

lua

can someone help me with lua "regex" aka patterns?

How do I translate this regex into a lua pattern for string.match(): ytplayer\.config\s*=\s*(\{.+?\});. You can use this site for an explanation what this regex does: https://regex101.com/#pcre

Essentially I want to look for a string which starts with ytplayer.config = (note the possible whitespace before and after equal sign), followed by a { and until we hit a semicolon.

ytplayer.config = {a lot of text, special characters and everything else which is possible...}}; this could be a result.

At the moment I have string.match(s, "ytplayer.config%s=%s({.});") but it returns an exact copy (checked with kdiff).

like image 203
sceiler Avatar asked Aug 22 '26 11:08

sceiler


1 Answers

Have a look, this will return your captured group:

print(string.match("ytplayer.config = {a lot of text, special characters and everything else which is possible...}};", "^ytplayer%.config%s*=%s*({.-});"))

Output:

{a lot of text, special characters and everything else which is possible...}}

The regex is ^ytplayer%.config%s*=%s*({.-});. In case you do not want check for a string start, remove ^ from the beginning.

Please see this demo.

In Lua patterns, % escspes "magic symbols". Like *, the modifier - also matches zero or more occurrences of characters of the original class. However, instead of matching the longest sequence, it matches the shortest one.

like image 153
Wiktor Stribiżew Avatar answered Aug 24 '26 02:08

Wiktor Stribiżew