How to Convert Perl Compatible Regular Expressions (PCRE) into Lua


A regular expression is a special text string that is used to describe a search pattern.

PCRE (Perl Compatible Regular Expressions) is a C library implementing regex. It was written in 1997 when Perl was the de-facto choice for complex text processing tasks. The syntax for patterns used in PCRE closely resembles Perl. If you want to learn about PERL and its use cases, you should visit this link.

Now, let's take an example to see how to convert a PCRE into Lua and then print it.

Example

Consider the code shown below −

"\002\003\004\005\006\007\008\009\010\011\012\

The above string acts as a PCRE and we will convert it into a Lua string with the help of Lua string library functions and a regex.

The regex will look something like this −

"[\002-\009\011-\026\#?`(){}%[%]^*<>=~|; \"!$&'\130-\255])", "\%1"

Example

The code for converting the above PCRE into Lua string is shown below −

 Live Demo

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

Output

\\\\\\\\'
'\\\'
'

Updated on: 20-Jul-2021

392 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements