【问题标题】:Match word which is not enclosed in quotes in Lua匹配 Lua 中未包含在引号中的单词
【发布时间】:2017-05-10 15:57:13
【问题描述】:

(对不起,我的英语不好)
我正在尝试匹配字符串中的or,如果它没有用单引号括起来,则用减号(-)替换它。 例如:

local input1 = "'condition1' or 'condition2'" 
input1:gsub(pattern, "-")  --> Should return "'condition1' - 'condition2'"

local input2 = "'condition1 or condition2'"  -- Note the position of the '
input2:gsub(pattern, "-")  --> Should return "'condition1 or condition2'"

pattern 是我要求的 Lua 模式。

我确定我必须使用%b'' 来检测or 是否被引用,所以我尝试了这个作为我的模式:[^%b'']or 但这对我不起作用。

请注意,我只能使用纯 Lua 库(所以不能使用 LPeg),因为代码将在不支持 C 库的不同 Lua 运行时(所有 5.2)中运行。

请注意,这个问题不是重复的 - 毫无疑问询问如何使用自己的模式在 Lua 中进行此操作

【问题讨论】:

  • 使用pattern = "(%b'')%s+or%s+(%b'')"和替换使用'%1 - %2'

标签: lua lua-patterns


【解决方案1】:

试试input:gsub("('.-'.-)or","%1-")

这假定or 总是出现在带引号的字符串之后。它捕获从引用字符串到 or 之前的所有内容,并根据需要将其替换为捕获的文本,后跟 -

【讨论】:

    猜你喜欢
    • 2019-06-13
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    相关资源
    最近更新 更多