nginx string.match non posix

时间:2015-07-22 14:43:35

标签: nginx lua

我有一个字符串(str1),我希望在模式之后提取任何内容" mycode =",

local str1 = "ServerName/codebase/?mycode=ABC123";
local tmp1 = string.match(str1, "mycode=%w+");
local tmp2 = string.gsub(tmp1,"mycode=", "");

从日志中

tmp1 => mycode=ABC123
tmp2 => ABC123

有更好/更有效的方法吗?我相信lua字符串不遵循POSIX标准(由于代码库的大小)。

1 个答案:

答案 0 :(得分:1)

是的,在您的模式中使用捕获来控制从string.match返回的内容。

来自lua reference manual(强调我的):

  

在字符串s中查找pattern的第一个匹配项。如果找到一个,则匹配返回模式中的捕获;否则它返回零。如果pattern指定没有捕获,则返回整个匹配。第三个可选的数字参数init指定从哪里开始搜索;它的默认值是1,可以是负数。

它的工作原理如下:

> local str1 = "ServerName/codebase/?mycode=ABC123"
> local tmp1 = string.match(str1, "mycode=%w+")
> print(tmp1)
mycode=ABC123
> local tmp2 = string.match(str1, "mycode=(%w+)")
> print(tmp2)
ABC123