Search code examples
regexluamatchopenresty

Matching variable string with Lua


I'm fighting with the file search script
The x99999999 value is continuously variable. How can I find this value with lua match?
I need to find and change this variable.

/home/data_x99999999_abc_def_0.sh 

I actually have code that works but I'm not sure it's a correct regex.

local newpath = s:gsub("(_x)[^_]*(_)", "_static_")

Solution

  • I'm not sure it's a correct regex.

    Lua patterns are no regular expressions. Compared to regular expressions Lua's string pattens have a different syntax and are more limited.

    Your code

    local newpath = s:gsub("(_x)[^_]*(_)", "_static_")
    

    replaces "_x" followed by 0 or more non-underscore characters followed by "_" with "_static_"

    This is correct but not very elegant.

    1. the captures () are not necessary as you don't make use of them. So "_x[^_]*_" would achieve the same.
    2. if you know that only the x12345678 part changes and that there are only digits after x you can simply use "x%d+" and repalce it with "static". This matches "x" followed by 1 or more digits. Or you include the underscores.
    3. if you only want to match exactly 8 digits you could use "%d%d%d%d%d%d%d%d" or string.rep("%d",8)