Lua字符串查找-如何使用连字符处理字符串? [英] Lua string find - How to handle strings with a hyphen?

查看:97
本文介绍了Lua字符串查找-如何使用连字符处理字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字符串-每个字符串都有很多行,如下所示:

I have two strings - each string has many lines like the following:

string1 = "  DEFAULT-VLAN         | Manual     10.1.1.3      255.255.255.0 "
string2 = "  1       DEFAULT-VLAN                     | Port-based No    No"

我将第一个字符串分为以下字符串:"DEFAULT-VLAN","|","Manual" ... 然后,我想在字符串2中查找字符串1中的vlanName("DEFAULT-VLAN")的ID("1").

The first string I split into the following strings: "DEFAULT-VLAN", "|", "Manual"... Then I want to look up the ID ("1") in string2 for the vlanName ("DEFAULT-VLAN") from string1.

我使用以下代码找到正确的子字符串:

I use this code to find the correct substring:

vpos1, vpos2 = vlan:find("%d-%s-" .. vlanName .. "%s-|")

但是vpos1和vpos2为零;从vlanName中删除连字符(-")时,它正在工作.
Lua难道不应该避免在这样的字符串中转义特殊字符吗?字符串从我的C ++应用程序移交给了Lua,可能会有很多特殊字符.
有一种简单的方法可以解决这个问题吗?

But vpos1 and vpos2 are nil; When the hyphen ("-") is deleted from the vlanName it is working.
Shouldn't Lua take care to escape the special characters in such strings? The string is handed over from my C++ application to Lua and there may be lots of special characters.
Is there an easy way to solve this?

谢谢!

推荐答案

Lua不是魔术.表达式"%d-%s-" .. vlanName .. "%s-|"所做的所有操作都是连接一些字符串,从而生成最终字符串.它不知道该字符串打算用于什么.只有string.find知道这一点,并且不会对给定参数的使用方式产生任何影响.

Lua is not magic. All the expression "%d-%s-" .. vlanName .. "%s-|" does is concatenate some strings, producing a final string. It has no idea what that string is intended to be used for. Only string.find knows that, and it can't have any affect on how the parameter it is given will be used.

所以是的,vlanName将被解释为Lua模式.而且,如果您想使用特殊字符,则需要对它们进行转义.我建议为此使用string.gsub.就像这样:

So yes, vlanName will be interpreted as a Lua pattern. And if you want to use special characters, you will need to escape them. I would suggest using string.gsub for that. It'd be something like this:

vlanName:gsub("[%-...]", "%%%0")

...是要转义的其他任何字符.

Where ... are any other characters you want to escape.

这篇关于Lua字符串查找-如何使用连字符处理字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆