string - Lua 模式用于替换任何单词、字符、数字或符号,后跟特定字符串

标签 string lua lua-patterns

我想替换 Lua 中的任何单词、字符、数字或符号(; , . 除外),后跟字符串 "some-word\" 。更像是正则表达式中的“*”选项。 Lua中有没有类似'*'的东西?

示例:

some-word\\test -> some-word\\###

some-word\\b*ax#@$6; -> some-word\\###;

some-word\\?foo,> -> some-word\\###,

我正在使用的代码:

d = "some-word" 
p = (tostring(d).."\\[.%c%w%p^%;^%,^%.]+") 
c = "###" 
s = "testing some-word\\test-2 later some-word\\&^*; some-word\\set_34$ " 
print(p) 
res = (string.gsub(s,p,c)) print(res)

最佳答案

(some%-word)\[^;,.%s]* 有效,请注意:

  • -是Lua模式中的一个魔术字符,需要对其进行转义。
  • some%-word() 包围,因此可以使用 %1 捕获它。
  • 在字符类中,用^开头表示 以下内容的补充。

测试:

d = "some%-word" 
p = "(" .. d .. ")" .. "\\[^;,.%s]*"
c = "%1###" 
s = "testing some-word\\test-2 later some-word\\&^*; some-word\\set_34$ " 
print(p) 
res = string.gsub(s,p,c)
print(res)

输出:

(some%-word)\[^;,.%s]*
testing some-word### later some-word###; some-word###

关于string - Lua 模式用于替换任何单词、字符、数字或符号,后跟特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29271141/

相关文章:

arrays - 为什么这个 string.match 不能持续工作?

c++ - 如何推送字符数组?

python - 根据起始字母从数据框中的列中提取值

c - 如何暂停/恢复 Lua 命令的处理

lua - 在 lua 中创建一个匹配括号和字符串的模式

string - Lua 的 string.format 的转义字符串

string - 将字符串a转换为字符串b

python - 使用我的代码在 python 中将字符串转换为字典

c++ - 读取解码后的 JSON Lua 表

regex - 如何删除Lua中括号内的文本?