ngx.re.gsub special characters and variables

1,219 views
Skip to first unread message

Gordon Madarm

unread,
Aug 30, 2014, 5:10:18 PM8/30/14
to openre...@googlegroups.com
My HTML response body includes several strings such as:
listproducts.php?cat=1
listproducts.php?cat=2
listproducts.php?cat=3

I want to replace the entire string with the string "test", but am having difficulty due to the question mark symbol in the string. I tried escaping the ? with a % as well as a \ and $ without success, e.g.:

body_filter_by_lua 'ngx.arg[1] = ngx.re.gsub(ngx.arg[1],"listproducts.php%?cat=%d", "test") ';

1. What is the proper way to escape a literal ? in a string?
2. Assuming the string "listproducts.php?cat=1" is in a variable, how can I use ngx.re.gsub to substitute the string with my "test" string?

thanks!
- G

Yichun Zhang (agentzh)

unread,
Aug 30, 2014, 6:10:56 PM8/30/14
to openresty-en
Hello!

On Sat, Aug 30, 2014 at 2:10 PM, Gordon Madarm wrote:
> I want to replace the entire string with the string "test", but am having
> difficulty due to the question mark symbol in the string. I tried escaping
> the ? with a % as well as a \ and $ without success, e.g.:
>
> body_filter_by_lua 'ngx.arg[1] =
> ngx.re.gsub(ngx.arg[1],"listproducts.php%?cat=%d", "test") ';
>

See https://github.com/openresty/lua-nginx-module#special-pcre-sequences

In short, you need to escape once for the nginx string literal and
another time for Lua literal string. Better use
body_filter_by_lua_file instead of avoid double-escaping.

Regards,
-agentzh
Reply all
Reply to author
Forward
0 new messages