【问题标题】:Pattern matching in Lua to snip words at starting and end of text chunkLua 中的模式匹配以在文本块的开头和结尾截断单词
【发布时间】: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


【解决方案1】:

场景 1:无论是开始模式还是结束模式都应该被剥离

或者,您可以将其拆分为 2 个 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")

online Lua demo

详情

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

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

【讨论】:

  • Wiktor - 此模式无法正常工作。 string.gsub(your_string_here, "^%s*%S+%s*(.*%S)%s+%S+%s*$", "%1") 给出的解决方案需要更正。我已经接受了它而没有进行单元测试。无论字符串 ` 和某些文本通道 ` 中是否有空格,它都会被删除。 如何解决这个问题
  • 但是ideone.com/DxYI5S 准确地显示了some text 输入的" and some text channel " 结果 - 这不是你想要的吗?
  • 去掉**和...**前面的空格并执行。将有相同的输出(根据提到的模式,应该不是。)
  • 对不起,我不明白你的意思。您的字符串" and some text channel " 不包含**,也不包含...。两个 sn-ps 都产生 some text
  • s = string.gsub(" and some, text channel ", ",", "#")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多