Ole Tange
Ole Tange

Reputation: 33740

Lua: Convert PCRE into Lua

I understand Lua does not have PCRE. How can I convert this into Lua?

# Quote shell chars
$a =~ s/[\002-\011\013-\032\\\#\?\`\(\)\{\}\[\]\^\*\<\=\>\~\|\; \"\!\$\&\'\202-\377]/\\$&/go;
# quote newline as '\n'                                                                             
$a =~ s/[\n]/'\n'/go;

Is there a general converter that can convert any PCRE into Lua?

Upvotes: 1

Views: 398

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627341

You may use

local a = "\002\003\004\005\006\007\008\009\010\011\012\\\n"
res, _ = a:gsub("([\002-\009\011-\026\\#?`(){}%[%]^*<>=~|; \"!$&'\130-\255])", "\\%1")
res, _ = res:gsub("\n", "'\n'")
print(res)

See Lua code demo

Note that in Lua patterns, \ is not a special char, % is used to replace special chars (like [) and \ddd escapes reference the decimal, not octal codes.

Upvotes: 3

Related Questions