Lua“简单”字符串.gsub
我在字符串解析方面遇到了小问题。我有一个像这样的字符串:
footage/down/temp/cars_[100]_upper/cars_[100]_upper.exr
并且我很难使用 gsub 删除该字符串的一部分。通常我会这样做
lineA = footage/down/temp/cars_[100]_upper/cars_[100]_upper.exr
lineB = footage/down/temp/cars_[100]_upper/
newline = lineA:gsub(lineB, "")
,通常会给我'cars_[100]_upper.exr'
问题是gsub不喜欢字符串中的[]或其他特殊字符,并且与string.find不同,gsub没有选项使用“plain”标志取消模式搜索。
当我正在归档文件比较脚本时,我无法手动编辑行以包含特殊字符的转义字符。
任何使用 lineB
从 lineA
到换行符的帮助将不胜感激。
I've hit s small block with string parsing. I have a string like:
footage/down/temp/cars_[100]_upper/cars_[100]_upper.exr
and I'm having difficulty using gsub to delete a portion of the string. Normally I would do this
lineA = footage/down/temp/cars_[100]_upper/cars_[100]_upper.exr
lineB = footage/down/temp/cars_[100]_upper/
newline = lineA:gsub(lineB, "")
which would normally give me 'cars_[100]_upper.exr'
The problem is that gsub doesn't like the [] or other special characters in the string and unlike string.find gsub doesn't have the option of using the 'plain' flag to cancel pattern searching.
I am not able to manually edit the lines to include escape characters for the special characters as I'm doing file a file comparison script.
Any help to get from lineA
to newline using lineB
would be most appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还可以使用以下方法转义文本字符串 str 中的标点符号:
str:gsub ("%p", "%%%0")
You can also escape punctuation in a text string, str, using:
str:gsub ("%p", "%%%0")
摘自《Programming in Lua 2e》第 181 页:
因此,我们可以想出一个简单的函数来转义这些魔术字符,并将其应用到您的输入字符串 (
lineB
):当然会打印:
cars_[100]_upper.exr
。Taking from page 181 of Programming in Lua 2e:
So, we can just come up with a simple function to escape these magic characters, and apply it to your input string (
lineB
):Which of course prints:
cars_[100]_upper.exr
.您可以使用另一种方法,例如:
You may use another approach like: