Lua gsub - How to set max character limit in regex pattern

后端 未结 1 854
栀梦
栀梦 2021-01-22 15:01

From strings that are similar to this string:

|cff00ccffkey:|r value

I need to remove |cff00ccff and |r to get:

key: value

相关标签:
1条回答
  • 2021-01-22 15:16

    Lua patterns do not support range/interval/limiting quantifiers.

    You may repeat %w alphanumeric pattern eight times:

    local newString = string.gsub("|cff00ccffkey:|r value", "|c%w%w%w%w%w%w%w%w", "")
    newString = string.gsub(newString, "|r", "")
    print(newString)
    -- => key: value
    

    See the Lua demo online.

    You may also make it a bit more dynamic if you build the pattern like ('%w'):.rep(8):

    local newString = string.gsub("|cff00ccffkey:|r value", "|c" ..('%w'):rep(8), "")
    

    See another Lua demo.

    If your strings always follow this pattern - |c<8alpnum_chars><text>|r<value> - you may also use a pattern like

    local newString = string.gsub("|cff00ccffkey:|r value", "^|c" ..('%w'):rep(8) .. "(.-)|r(.*)", "%1%2")
    

    See this Lua demo

    Here, the pattern matches:

    • ^ - start of string
    • |c - a literal |c
    • " ..('%w'):rep(8) .. " - 8 alphanumeric chars
    • (.-) - Group 1: any 0+ chars, as few as possible
    • |r - a |r substring
    • (.*) - Group 2: the rest of the string.

    The %1 and %2 refer to the values captured into corresponding groups.

    0 讨论(0)
提交回复
热议问题