Lua:除非引用,否则将字符串拆分为单词 [英] Lua: split string into words unless quoted

查看:118
本文介绍了Lua:除非引用,否则将字符串拆分为单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下代码在空白之间分割字符串:

So I have the following code to split a string between whitespaces:

text = "I am 'the text'"
for string in text:gmatch("%S+") do
    print(string)
end

结果:

I
am
'the
text'

但是我需要这样做:

I
am
the text --[[yep, without the quotes]]

我该怎么做?

编辑:只是为了补充问题,这个想法是将参数从一个程序传递到另一个程序.这是我正在处理的请求请求,目前正在审核中: https://github.com /mpv-player/mpv/pull/1619

just to complement the question, the idea is to pass parameters from a program to another program. Here is the pull request that I am working, currently in review: https://github.com/mpv-player/mpv/pull/1619

推荐答案

也许有一些方法可以通过聪明的解析来做到这一点,但是另一种方法可能是跟踪简单状态并基于对引用片段的检测来合并片段.这样的事情可能会起作用:

There may be ways to do this with clever parsing, but an alternative way may be to keep track of a simple state and merge fragments based on detection of quoted fragments. Something like this may work:

local text = [[I "am" 'the text' and "some more text with '" and "escaped \" text"]]
local spat, epat, buf, quoted = [=[^(['"])]=], [=[(['"])$]=]
for str in text:gmatch("%S+") do
  local squoted = str:match(spat)
  local equoted = str:match(epat)
  local escaped = str:match([=[(\*)['"]$]=])
  if squoted and not quoted and not equoted then
    buf, quoted = str, squoted
  elseif buf and equoted == quoted and #escaped % 2 == 0 then
    str, buf, quoted = buf .. ' ' .. str, nil, nil
  elseif buf then
    buf = buf .. ' ' .. str
  end
  if not buf then print((str:gsub(spat,""):gsub(epat,""))) end
end
if buf then print("Missing matching quote for "..buf) end

这将打印:

I
am
the text
and
some more text with '
and
escaped \" text

已更新以处理混合和转义的引号.更新以删除引号.已更新以处理引号.

Updated to handle mixed and escaped quotes. Updated to remove quotes. Updated to handle quoted words.

这篇关于Lua:除非引用,否则将字符串拆分为单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆