// 用于提取/替换值的 Lua 模式
我有一个像 hello /world Today/
这样的字符串,
我需要用 /MY NEW STRING/
替换 /world Today/
阅读我的手册发现
newString = string.match("hello /world today/","%b//")
我可以使用 gsub
来替换它,但我想知道是否还有一种优雅的方法来返回 /
之间的文本,我知道我可以修剪它,但我想知道是否存在某种模式。
I have a string like hello /world today/
I need to replace /world today/
with /MY NEW STRING/
Reading the manual I have found
newString = string.match("hello /world today/","%b//")
which I can use with gsub
to replace, but I wondered is there also an elegant way to return just the text between the /
, I know I could just trim it, but I wondered if there was a pattern.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请尝试以下操作之一:
slashed_text = string.match("hello /world Today/", "/([^/]*)/")
slashed_text = string.match( “你好/今天的世界/”,“/(.-)/”)
slashed_text = string.match(“你好/今天的世界/”,“/(.*)/”)
这是有效的,因为
string.match
返回模式中的任何捕获,如果没有捕获,则返回整个匹配的文本。那么关键是要确保模式具有适当的贪婪程度,记住 Lua 模式不是完整的正则表达式语言。前两个应该匹配相同的文本。首先,我明确要求模式匹配尽可能多的非斜杠。第二个(感谢 lhf)匹配所有字符的最短跨度,后跟斜杠。第三个比较贪婪,它匹配后面仍可以跟斜杠的最长字符跨度。
原始问题中的
%b//
与/.-/
相比没有任何优势,因为这两个分隔符是相同的字符。编辑:添加了 lhf 建议的模式以及更多解释。
Try something like one of the following:
slashed_text = string.match("hello /world today/", "/([^/]*)/")
slashed_text = string.match("hello /world today/", "/(.-)/")
slashed_text = string.match("hello /world today/", "/(.*)/")
This works because
string.match
returns any captures from the pattern, or the entire matched text if there are no captures. The key then is to make sure that the pattern has the right amount of greediness, remembering that Lua patterns are not a complete regular expression language.The first two should match the same texts. In the first, I've expressly required that the pattern match as many non-slashes as possible. The second (thanks lhf) matches the shortest span of any characters at all followed by a slash. The third is greedier, it matches the longest span of characters that can still be followed by a slash.
The
%b//
in the original question doesn't have any advantages over/.-/
since the the two delimiters are the same character.Edit: Added a pattern suggested by lhf, and more explanations.