Search code examples
stringlualua-patterns

Lua pattern to select particular string followed by any word


Can anyone please let me know why I am not able to select CWIND7x32\ab_c1 in the below code?

s="[cC][wW][iI][nN]7[xX]32"
local p= (tostring(s).."\\([%%w_]+)?")
local c = "##\\##"
print(p)
tstr = "Pattern CWINd7x32\\ab_c1 is valid"
print(tstr)
res=string.gsub(tstr,p,c)
print(res)

I want a pattern to select any word which is in the format CWINDX32\any word, where CWINDX32 should be case insensitive word.

Note that the word can have alpha-numeric characters and underscore only and may be terminated by whitespace or ; or , or :

Example:

Pattern CWINd7x32\ab_c1 is valid -> Pattern ##\## is valid

Pattern cWIND7x32\efg; is valid -> Pattern ##\##; is valid

Pattern CWIND7X32\random_user, is valid -> Pattern ##\##, is valid


Solution

  • First, you missed [dD] in the pattern, which I guess is a typo.

    There are still some other problems.

    • ? in Lua patterns only applies to a single character, so "\\([%%w_]+)?" is invalid.
    • %% is the escaped % character, [%%w_] matches a % character, a w or an underscore _, wihch is not what you expected.

    The fixed pattern is [cC][wW][iI][nN][dD]7[xX]32\[%w_]+.