“string.find”失败了,原因是有一个连字符。

huangapple go评论69阅读模式
英文:

string.find fails with a hyphen

问题

我用Lua开始制作Factorio模组,出现了一个有趣的问题:我无法正确执行Lua中的简单子字符串搜索。string.find可以正确找到"-mining-"或"-drones",但不能同时找到带有连字符的两个单词。如何修复这个问题?

local str = "copper-ore-mining-drone-10"
local sub = "mining-drone"
print(str:find(sub))

快速测试链接:
https://www.lua.org/cgi-bin/demo

也许find使用了某种模式语法,连字符并非字面意义上的字符?但我在文档中找不到相关信息,并且尝试转义它-"会导致"无效的转义序列"错误。如果需要进行某种转义,我如何可以自动完成?因为我从外部来源接收子字符串值。

英文:

I started making Factorio mods with Lua, and a funny problem appeared: I cannot correctly perform a simple substring search in Lua. string.find can correctly find "-mining-" or "-drones", but not both words with a hyphen. How to fix this??

local str = "copper-ore-mining-drone-10"
local sub = "mining-drone"
print(str:find(sub))

For quick testing:
https://www.lua.org/cgi-bin/demo

Maybe find uses some pattern syntax and a hyphen isn't used literally? But I found nothing about it in the docs, and trying to escape it -" leads to invalid escape sequence error. In case it requires some escaping, how can I do this automatically? Cuz I receive substring value from an external source.

答案1

得分: 2

经过更多搜索,我发现find方法实际上使用了一些表达式语法(奇怪的是文档中没有解释)。有一些解决方法:

1. 使用转义符号%

看起来Lua的搜索表达式语法使用%作为转义字符:

str:find("mining%-drone")

2. 设置plain标志

该方法有一些参数,这些参数也没有在文档中提到,第三个参数是plain标志,它允许将子字符串视为字面值:

str:find(sub, 1, true)
英文:

After more googling, I found that yeah, find method really uses some expression syntax (strange that it's not explain in the docs). There is a couple of solutions:

1. Use escape symbol %

Seems like lua's search expression syntax uses % as an escape character:

str:find("mining%-drone")

2. Set plain flag

The method has some arguments that also aren't mention in the docs, the third one is plain flag which allows to treat a substring literally:

str:find(sub, 1, true)

huangapple
  • 本文由 发表于 2023年5月26日 16:24:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76338986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定