简体   繁体   中英

Lua: how do I split a string (of a varying length) into multiple parts?

I have a string, starting with a number, then a space, then a word of an unknown amount of letters, a space again, and then sometimes another piece of text (which may or may not contain more than one word).

EDIT: the last piece of text is sometimes left out (see example #2) Using the methods mentioned in the comments, str:find(...) on #2 would return nil.

Example:

"(number) (text) [more text]"
1: "10 HELLO This is a string"
2: "88 BYE"

What I want is to split these strings into a table, inside a table containing more of these split strings, like this:

{
  [(number)] = { [1] = (text), [2] = (more text) }
  [10] = { [1] = "HELLO", [2] = "This is a string" }
}

I have tried several methods, but none of them give me the desired result. One of the methods I tried, for example, was splitting the string on whitespaces. But that resulted in:

{
  [10] = { [1] = "HELLO", [2] = "This", ... [4] = "string" }
}

Thanks in advance.

Using various Lua string patterns , achieving the desired result is quite easy.

For eg.

function CustomMatching( sVar )
    local tReturn = {}
    local _, _, iNumber, sWord, sRemain = sVar:find( "^(%d+)%s(%a+)%s(.+)" )
    tReturn[tonumber(iNumber)] = { sWord, sRemain }
    return tReturn
end

And to call it:

local sVar = "10 HELLO This is a string"
local tMyTable = CustomMatching( sVar )

In the find() method the pattern "^(%d+)%s(%a+)%s(.+)" means:

  • Find and store all digits( %d ) until a space is encountered.
  • Find and store all letters( %a ) until a space is encountered.
  • Find and store all characters until the end of string is reached.

EDIT

Changed tReturn[iNumber] to tReturn[tonumber(iNumber)] as per the discussion in comments .

You can use the string.match method with an appropriate pattern :

local n, w, str = ('10 HELLO This is a string'):match'^(%d+)%s+(%S+)%s+(.*)$'
your_table[tonumber(n)] = {w, str}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM