Lua: 如何在一个字符后开始匹配

Lua: How to start match after a character

我正在尝试制作一个搜索功能,允许您在插入 | 时将搜索一分为二。字符并搜索您输入的内容。

到目前为止,我已经了解了如何通过在 space 之前捕获来保留主命令。

例如,如果我输入 :ban user,下面的框仍会显示 :ban,但就在我输入 | 时,它会重新开始搜索。

:ba
:ba

:ban user|:at
:at

:ban user|:attention members|:kic
:kic

此代码:

text=":ban user|:at"
text=text:match("(%S+)%s+(.+)")
print(text)

仍会return禁止。

I'm trying to get a match of after the final | character.

然后你可以使用

text=":ban user|:at"
new_text=text:match("^.*%|(.*)") 
if new_text == nil then new_text = text end
print(new_text)

Lua demo

解释:

  • .* - 尽可能多地匹配任何 0+ 个字符 (以 "greedy" 的方式,因为整个字符串被抓取然后回溯发生找到...)
  • %| - 最后一个文字 |
  • (.*) - 匹配并捕获任何 0+ 个字符(直到字符串末尾)。

为避免特殊情况,请确保字符串始终具有 |:

function test(s)
    s="|"..s
    print(s:match("^.*|(.*)$"))
end

test":ba"
test":ban user|:at"
test":ban user|:attention members|:kic"