在lua中使用指定的分隔符拆分字符串

时间:2016-10-20 08:47:31

标签: regex lua

我尝试在lua中使用分隔符创建split()函数,当默认为空格时。 默认工作正常。当我给函数分隔符时,问题就开始了。由于某种原因,它不会返回最后一个子字符串。 功能:

local str = "a,b,c,d,e,f,g"
local sep = ","
t = split(str,sep)
for i,j in ipairs(t) do
    print(i,j)
end

我尝试运行:

1   a
2   b
3   c
4   d
5   e
6   f

我得到了:

db._explain(<your query here>);

无法弄清楚错误的位置......

3 个答案:

答案 0 :(得分:6)

分割字符串时,避免极端情况的最简单方法是将分隔符附加到字符串,当您知道字符串不能以分隔符结束时:

str = "a,b,c,d,e,f,g"
for w in str:gmatch("([^,]+)") do print(w) end

或者,您可以使用带有可选分隔符的模式:

VALIDATION
    'ct' '^[a-zA-Z\-]+$'
    'default_ct' ''  # <-- ct will be a empty string if not provided via URL 
END
FILTER (([ct]='%ct%') or  ('%ct%' = '') )

实际上,我们不需要可选的分隔符,因为我们正在捕获非分隔符:

ct

答案 1 :(得分:0)

这里是我通常用于所有&#34;分裂&#34;的分割功能。需要:

function split(s, sep)
    local fields = {}

    local sep = sep or " "
    local pattern = string.format("([^%s]+)", sep)
    string.gsub(s, pattern, function(c) fields[#fields + 1] = c end)

    return fields
end

t = split("a,b,c,d,e,f,g",",")
for i,j in pairs(t) do
    print(i,j)
end

答案 2 :(得分:0)

"[^"..sep.."]*"..sep这是导致问题的原因。您正在匹配一个字符串,这些字符不是分隔符后跟分隔符。但是,您要匹配的最后一个子字符串(g)后面没有分隔符。

解决此问题的最快方法是将\0视为分隔符("[^"..sep.."\0]*"..sep),因为它代表字符串的开头和/或结尾。这样,g,后面没有分隔符,但是字符串的末尾仍然被视为匹配。

我说你的方法一般过于复杂;首先,您可以匹配不包含分隔符的各个子字符串;其次,您可以使用for函数

gmatch循环中执行此操作
local result = {}
for field in your_string:gsub(("[^%s]+"):format(your_separator)) do
  table.insert(result, field)
end
return result

编辑:上面的代码更简单:

local pattern = "[^%" .. your_separator .. "]+"
for field in string.gsub(your_string, pattern) do
-- ...and so on (The rest should be easy enough to understand)

EDIT2:请记住,你也应该逃脱你的分隔符。如果您不将%

转义为%%,则function escape(str) return str:gsub("([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1") end 之类的分隔符可能会导致问题
import pandas as pd

values = ['false','true','false','false','false','true','true','true','false']
df = pd.DataFrame(values,columns=['values'])

print "Before changes: "
print df

to_become_false = df[df['values'] == 'true'].index.tolist()
to_become_true = [idx+1 for idx in to_become_false if not(idx+1 in to_become_false)]
df['values'][to_become_false] = 'false'
df['values'][to_become_true] = 'true'

print "\n\nAfter changes: "
print df
相关问题