在Lua中用字符分割字符串 [英] Split a string by a character in Lua
本文介绍了在Lua中用字符分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有像"ABC-DEF"
这样的字符串,我需要用"-"
字符将它们分割,然后将两个部分分别分配给一个变量.在Ruby中,我会这样做:
I have strings like "ABC-DEF"
and I need to split them by the "-"
character and assign each of the two parts to a variable. In Ruby, I would do it like:
a, b = "ABC-DEF".split('-')
显然,Lua没有这么简单的方法.经过一番挖掘,我找不到一种简短的方法来实现自己的目标.我提到我是Lua的完全新手,我需要在Redis脚本中使用它(因此,它的大小应该确实很小,如果可能的话,只能写一个).
Apparently, Lua doesn't have such an easy way. After some digging, I couldn't find a short and concise way to achieve what I'm after. I mention I am a complete newbie to Lua and I need to use it in a script for Redis (so it should indeed be small, a one liner if possible).
推荐答案
使用模式匹配:
a, b = string.match("ABC-DEF", "(.*)%-(.*)")
请注意,-
是一个魔法人物,因此必须使用%
对其进行转义.
Note that -
is a magic character, so it must be escaped with %
.
这篇关于在Lua中用字符分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文