1

I have the following string:

example = "1,3,4-7,9,13-17"

With these values ​​I want the next array: 1,3,4,5,6,7,9,13,14,15,16,17

With the script below I get the values ​​between the commas, but how do I get the rest.

teststring = "1,3,4-7,9,13-17"
testtable=split(teststring, ",");
for i = 1,#testtable do
  print(testtable[i])
end;

function split(pString, pPattern)

  local Table = {}  -- NOTE: use {n = 0} in Lua-5.0
  local fpat = "(.-)" .. pPattern
  local last_end = 1
  local s, e, cap = pString:find(fpat, 1)
  while s do
    if s ~= 1 or cap ~= "" then
      table.insert(Table,cap)
    end
    last_end = e+1
    s, e, cap = pString:find(fpat, last_end)
  end
  if last_end <= #pString then
    cap = pString:sub(last_end)
    table.insert(Table, cap)
 end
 return Table
end

Output

1

3

4-7

9

13-17

2 Answers 2

3

The following code solves your problem, given that your input string sticks to that format

local test = "1,3,4-7,8,9-12"
local numbers = {}
for number1, number2 in string.gmatch(test, "(%d+)%-?(%d*)") do
  number1 = tonumber(number1)
  number2 = tonumber(number2)

  if number2 then
    for i = number1, number2 do
      table.insert(numbers, i)
    end
  else
    table.insert(numbers, number1)
  end

end

First we use string.gmatch to iterate over the string. The pattern will match one or more digits, followed by one or zero "-", followed by zero or more digits. By using captures we make sure that number1 is the first number and number2 is the second number if we actually have an interval given. If we have an interval given we create the numbers in between using a for loop from number1 to number2. If we don't have an interval number2 is nil and we only have number1so we only insert that.

Please refer to the Lua Reference Manual - Patterns and string.gmatch for further details

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for this solution. This is what I was looking for.
0

Here's another approach:

for _, v in ipairs(testtable) do    
  if string.match(v,'%-') then
    local t= {}
    for word in string.gmatch(v, '[^%-]+') do
      table.insert(t, word)
    end    
    for i = t[1],t[2] do print(i) end        
  else
   print (v)
  end
end

1 Comment

note that you don't need a capture if your pattern only consists of what you capture.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.