Table of Contents

lua分割字符串

local ngx_find    = ngx.re.find

local function split(str, sep , count)
local t = {}
count = count or -1

<span class="kd">local</span> <span class="n">nfield</span><span class="p">,</span> <span class="n">nstart</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span>
<span class="kd">local</span> <span class="n">nfirst</span><span class="p">,</span><span class="n">nlast</span> <span class="o">=</span> <span class="nb">string.find</span><span class="p">(</span><span class="n">str</span><span class="p">,</span> <span class="n">sep</span><span class="p">)</span>
<span class="c1">-- local nfirst,nlast = ngx_find(str, sep, &#34;jo&#34;)</span>
<span class="kr">while</span> <span class="n">nfirst</span> <span class="ow">and</span> <span class="n">count</span> <span class="o">~=</span> <span class="mi">0</span> <span class="kr">do</span>
    <span class="n">t</span><span class="p">[</span><span class="n">nfield</span><span class="p">]</span> <span class="o">=</span> <span class="nb">string.sub</span><span class="p">(</span><span class="n">str</span><span class="p">,</span> <span class="n">nstart</span><span class="p">,</span> <span class="n">nfirst</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span>
    <span class="n">nfield</span> <span class="o">=</span> <span class="n">nfield</span><span class="o">+</span><span class="mi">1</span>
    <span class="n">nstart</span> <span class="o">=</span> <span class="n">nlast</span><span class="o">+</span><span class="mi">1</span>
    <span class="n">nfirst</span><span class="p">,</span><span class="n">nlast</span> <span class="o">=</span> <span class="nb">string.find</span><span class="p">(</span><span class="n">str</span><span class="p">,</span> <span class="n">sep</span><span class="p">,</span> <span class="n">nstart</span><span class="p">)</span>
    <span class="c1">-- nfirst,nlast = ngx_find(str, sep, &#34;jo&#34;, nil, nstart)</span>
    <span class="n">count</span> <span class="o">=</span> <span class="n">count</span><span class="o">-</span><span class="mi">1</span>
<span class="kr">end</span>
<span class="n">t</span><span class="p">[</span><span class="n">nfield</span><span class="p">]</span> <span class="o">=</span> <span class="nb">string.sub</span><span class="p">(</span><span class="n">str</span><span class="p">,</span> <span class="n">nstart</span><span class="p">)</span>
<span class="kr">return</span> <span class="n">t</span>

end