Lua 中的模式匹配,用于剪去文本块开头和结尾的单词

我的目标是找到一个类似于下面这样的模式,

  space channel space

我想要剪掉文本块(页)的开头和结尾。

我在 Lua 中编写了以下代码。我的下面的代码只适用于一个字母的模式。

我应该如何使它适用于任何具有此 space word space 模式的单词,该模式应裁剪出出现在 页面开头和结尾的数组索引值?

singleChar = ' and third party cookies (such as the DoubleClick cookie) together to (a) inform, optimize and serve ads based on a users past visits to '

totaLen = string.len(singleChar)

totalen = -totaLen

print('actual singleChar - '..singleChar)

singleCharChecking = string.sub(singleChar,-2,-1)

print ('singleCharChecking - '..singleCharChecking)

checkPattern = string.gmatch(singleCharChecking,"%s%a")

for word in checkPattern do
    checkPatternLen = string.len(word)
    print(checkPatternLen)
    if (checkPatternLen == 2) then
        singleChar = string.sub(singleChar,totalen,-2)
        print('single char - '..singleChar)
    end
end

输入:singleChar = ' and third party cookies (such as the DoubleClick cookie) together to (a) inform, optimize and serve ads based on a users past visits to '

期望的输出: third party cookies (such as the DoubleClick cookie) together to (a) inform, optimize and serve ads based on a users past visits

点赞
用户3832970
用户3832970

情况1:应剥离开头或结尾的模式

或者,您可以将其拆分为两个 gsub 操作,从而使其变得不那么复杂:

local s = string.gsub(" and some text channel ", "^%s+%S+%s+", "")
s = s:gsub("%s+%S+%s*$", "")

第一行将删除初始的 1+ 空格、1+ 非空格、1+ 空格,第二行将条纹字符串末尾相同的模式。

情况2:如果必须同时存在起始和结束模式

由于您想要从字符串中删除第一个和最后一个非空格块,因此可以使用

string.gsub(" and some text channel ", "^%s+%S+%s+(.*%S)%s+%S+%s+$", "%1")

请参见在线 Lua 演示

详细信息

  • ^ - 字符串的开头
  • %s+ - 1+ 空格
  • %S+ - 1+ 非空格
  • %s+ - 1+ 空格
  • (.*%S) - 组1捕获 0+ 字符 贪婪地一直到最后一个非空格字符,然后是
  • %s+%S+%s*$ - 字符串末尾的 1+ 空格 (%s+),1+ 非空格 (%S+) 和 0+ 空格 (%s*) ($)。

替换部分中的 %1 将组1内容重新插入结果。

2016-12-05 13:47:05