das
das

Reputation: 547

Split string by dot lua, yet retain double and triple dots

I'm trying to split a string by a single dot, yet retain double(and more) dots.

My approach is like this,which works only with double dots:

local s = "some string.. with several dots, added....more dots.another line inserted."; for line in s:gsub('%.%.','#&'):gmatch('[^%.]+') do print(line:gsub('#&','..')); end

Another approach was like this

print(s:match('([^%.]+[%.]*[^%.]+)'))

which halts after the next sequence of dots, so it does not suit properly.

How could I accomplish this in a pattern matching?

Upvotes: 3

Views: 1253

Answers (2)

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23747

local s = 'some string.. with several dots, added....more dots.another line inserted.'
for line in s:gsub("%f[.]%.%f[^.]", "\0"):gmatch"%Z+" do 
   print(line) 
end

Upvotes: 2

tonypdmtr
tonypdmtr

Reputation: 3225

An alternative approach:

local s = 'some string.. with several dots, added....more dots.another line inserted.'

function split_on_single_dot(s)
  local ans, old_pos = {}, 1
  for pos,dots in (s..(s:sub(-1) == '.' and '' or '.')):gmatch '()(%.+)' do
    if #dots == 1 then
      ans[#ans+1] = s:sub(old_pos,pos-1)
      old_pos = pos+1
    end
  end
  return ipairs(ans)
end

-- test
for i,v in split_on_single_dot(s) do print(i,v) end

Upvotes: 0

Related Questions