【发布时间】:2017-04-19 20:47:07
【问题描述】:
我的目标是找到类似于下面的模式,
space channel space
我想在开始和结束的文本块(页面)中剪掉。
我在 Lua 中编写了以下代码。我下面的代码仅适用于 1 个字母模式。
我应该如何使它适用于具有这种 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 = ' 和第三方 cookie(例如 DoubleClick cookie)一起(a)根据用户过去对'的访问来通知、优化和投放广告
预期输出: 第三方 cookie(例如 DoubleClick cookie)一起(a)根据用户过去的访问通知、优化和投放广告
【问题讨论】:
-
能否提供一个示例字符串和预期输出?
-
Wiktor - 请在上面找到更新
-
那么,您想从字符串中删除第一个和最后一个非空白块吗?试试
string.gsub(your_string_here, "^%s*%S+%s*(.*%S)%s+%S+%s*$", "%1")(见demo)。 -
感谢您使用小代码 sn-p。您可以将此作为答案发布。 (但是我仍然面临与您的解决方案无关的问题。您的解决方案运行良好。)
-
你能告诉我你是如何得到这种模式和限制的吗(%1)
标签: arrays string lua pattern-matching