Search code examples
regexluapattern-matchinglua-patterns

Regex as Lua pattern


I wrote (?<=;)[^\^]* regex but I have problem with transforming it to use it in Lua. I want to transform

^#57df44;Cobblestone^white;

into

Cobblestone

but if the string does not contain any color code then it should be returned "as is".

Could someone help me with this?


Solution

  • Use a capturing group:

    local s = "^#57df44;Cobblestone^white;"
    res = s:match(";([^^]*)") or s
    print( res )
    -- Cobblestone
    

    See the Lua demo.

    Here,

    • ; - matches the first ;
    • ([^^]*) - Capturing group 1 matches any 0+ chars other than ^ into Group 1

    The string.match will only return the captured part if the capturing group is defined in the pattern.

    More details

    As is mentioned in comments, you might use a frontier pattern %f[^:] instead of (?<=:) in the current scenario.

    The frontier pattern %f followed by a set detects the transition from "not in set" to "in set".

    However, the frontier pattern is not a good substitute for a positive lookbehind (?<=:) because the latter can deal with sequences of patterns, while a frontier pattern only works with single atoms. So, %f[^:] means place in string between : and a non-:. Howerver, once you need to match any 0+ chars other than ^ after city=, a frontier pattern would be a wrong construct to use. So, it is not that easily scalable as a string.match with a capturing group.