我需要做一个简单的字符串分割,但似乎没有一个函数,我测试的手动方式似乎不起作用。我该怎么做呢?
当前回答
你可以使用penlight图书馆。它有一个使用分隔符分割字符串的函数,输出列表。
它实现了许多我们在编程时可能需要和Lua中缺少的功能。
下面是使用它的示例。
>
> stringx = require "pl.stringx"
>
> str = "welcome to the world of lua"
>
> arr = stringx.split(str, " ")
>
> arr
{welcome,to,the,world,of,lua}
>
其他回答
根据用例,这可能是有用的。它将剪切标志两侧的所有文本:
b = "This is a string used for testing"
--Removes unwanted text
c = (b:match("a([^/]+)used"))
print (c)
输出:
string
我有一个非常简单的解决办法。使用gmatch()函数捕获包含除所需分隔符以外的至少一个字符的字符串。分隔符默认为任何空格(Lua中的%s):
function mysplit (inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={}
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
table.insert(t, str)
end
return t
end
如果你只想遍历这些令牌,这是非常简洁的:
line = "one, two and 3!"
for token in string.gmatch(line, "[^%s]+") do
print(token)
end
输出:
一个, 两个 而且 3!
简单解释:“[^%s]+”模式匹配空格字符之间的每个非空字符串。
因为剥猫皮的方法不止一种,下面是我的方法:
代码:
#!/usr/bin/env lua
local content = [=[
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
]=]
local function split(str, sep)
local result = {}
local regex = ("([^%s]+)"):format(sep)
for each in str:gmatch(regex) do
table.insert(result, each)
end
return result
end
local lines = split(content, "\n")
for _,line in ipairs(lines) do
print(line)
end
输出: 圣洁圣洁的人, sed做eiusmod时间incididunt ut并dolore麦格纳 aliqua。Ut enim ad minivenim, quis nostrud practice 这一切都是徒劳的结果。
解释:
gmatch函数作为一个迭代器,它获取所有与regex匹配的字符串。正则表达式接受所有字符,直到找到分隔符为止。
你可以使用penlight图书馆。它有一个使用分隔符分割字符串的函数,输出列表。
它实现了许多我们在编程时可能需要和Lua中缺少的功能。
下面是使用它的示例。
>
> stringx = require "pl.stringx"
>
> str = "welcome to the world of lua"
>
> arr = stringx.split(str, " ")
>
> arr
{welcome,to,the,world,of,lua}
>
推荐文章
- Printf与std::字符串?
- 不区分大小写的“in”
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 如何在PHP中截断字符串最接近于一定数量的字符?
- Ruby数组到字符串的转换
- 为什么在Java和。net中不能修改字符串?
- 如何创建一个日期对象从字符串在javascript
- 在Android上将字符串转换为整数
- 删除字符串的最后3个字符
- 如何大写一个字符串的第一个字母在省道?
- 不区分大小写的列表排序,没有降低结果?
- indexOf()和search()的区别是什么?
- 我如何在Swift连接字符串?
- 如何获得一个变量值,如果变量名存储为字符串?
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?