tianheng 发表于 2013-8-19 13:38:03

string.gsub使用中的疑惑

string.gsub使用中的疑惑
function teststr()
        local str = "down,northeast,east,north ,south,southeast,out";
        print(string.gsub(str, "out", "", 1));
end
输出为:down,northeast,east,north ,sh,southeast,out 1

期望是:down,northeast,east,north ,south,southeast, 1

怎么用,盼指点

北大侠客行MUD,中国最好的MUD

tianheng 发表于 2013-8-19 14:20:15

本帖最后由 tianheng 于 2013-8-19 02:34 PM 编辑

自己写了个替换函数,无奈不熟悉正则
function teststr()
      local str = "down,northeast,east,north,south,southeast,out,up";
      print(str);
      print(string.find(str, "out"));
      print(string.gsub(str, "out", "", 1));
      
      print(delstr(str, ",", "out"));
end

function delstr(str, p, s)
      local t = utils.split(str, p)
      local r = {}
      for k, v in pairsByKeys(t) do
                if v ~= s then
                        table.insert(r, v)
                end
      end
      return table.concat(r, p)
end
结果:
down,northeast,east,north,south,southeast,out,up 28 30
down,northeast,east,north,sh,southeast,out,up 1
down,northeast,east,north,south,southeast,up

emyt 发表于 2013-8-19 15:27:18

function teststr()
      local str = "down,northeast,east,north ,south,southeast,out";
      print(string.gsub(str, ",out", "", 1));
end这样写不就行了

emyt 发表于 2013-8-19 15:30:15

有时候换个思路就好,
还有str = "down,northeast,east,north ,south,southeast,out"
引号里是一个字符串 "," 逗号也是字符串的元素之一,gsub是针对整个字符串操作的当然出这样的结果

tianheng 发表于 2013-8-19 19:09:01

out是第一个呢?

emyt 发表于 2013-8-20 10:05:43

local str = "down,northeast,east,north ,south,southeast,out"
print(string.gsub(string.gsub(str,",out", "", 1),"out,", "", 1))

emyt 发表于 2013-8-20 10:06:01

有思路照搬一次就行了啊
页: [1]
查看完整版本: string.gsub使用中的疑惑