Lua gsub-如何在正则表达式模式中设置最大字符数限制 [英] Lua gsub - How to set max character limit in regex pattern
问题描述
从与此字符串相似的字符串中:
From strings that are similar to this string:
|cff00ccffkey:|r value
我需要除去| cff00ccff和| r才能得到:
I need to remove |cff00ccff and |r to get:
key: value
问题在于|cff00ccff
是颜色代码.我知道它总是以|c
开头,但是接下来的8个字符可以是任何东西.因此,我需要一个gsub模式来获取|c
之后的下8个字符(仅字母数字).
The problem is that |cff00ccff
is a color code. I know it always starts with |c
but the next 8 characters could be anything. So I need a gsub pattern to get the next 8 characters (alpha-numeric only) after |c
.
如何在Lua中做到这一点?我已经尝试过:
How can I do this in Lua? I have tried:
local newString = string.gsub("|cff00ccffkey:|r value", "|c%w*", "")
newString = string.gsub(newString, "|r", "")
但是这将删除所有内容,直到第一个空格,而且我不知道如何指定要选择的最大字符数来避免这种情况.
but that will remove everything up to the first white-space and I don't know how to specify the max characters to select to avoid this.
谢谢.
推荐答案
Lua patterns do not support range/interval/limiting quantifiers.
您可以重复八次%w
字母数字模式:
You may repeat %w
alphanumeric pattern eight times:
local newString = string.gsub("|cff00ccffkey:|r value", "|c%w%w%w%w%w%w%w%w", "")
newString = string.gsub(newString, "|r", "")
print(newString)
-- => key: value
在线观看 Lua演示.
如果您构建类似('%w'):.rep(8)
的模式,也可以使其更具动态性:
You may also make it a bit more dynamic if you build the pattern like ('%w'):.rep(8)
:
local newString = string.gsub("|cff00ccffkey:|r value", "|c" ..('%w'):rep(8), "")
请参见另一个Lua演示.
如果您的字符串始终遵循此模式-|c<8alpnum_chars><text>|r<value>
-您也可以使用类似模式
If your strings always follow this pattern - |c<8alpnum_chars><text>|r<value>
- you may also use a pattern like
local newString = string.gsub("|cff00ccffkey:|r value", "^|c" ..('%w'):rep(8) .. "(.-)|r(.*)", "%1%2")
请参见此Lua演示
此处,模式匹配:
-
^
-字符串开头 -
|c
-文字|c
-
" ..('%w'):rep(8) .. "
-8个字母数字字符 -
(.-)
-第1组:任意0个以上的字符,数量尽可能少 -
|r
-一个|r
子字符串 -
(.*)
-第2组:字符串的其余部分.
^
- start of string|c
- a literal|c
" ..('%w'):rep(8) .. "
- 8 alphanumeric chars(.-)
- Group 1: any 0+ chars, as few as possible|r
- a|r
substring(.*)
- Group 2: the rest of the string.
%1
和%2
是指捕获到相应组中的值.
The %1
and %2
refer to the values captured into corresponding groups.
这篇关于Lua gsub-如何在正则表达式模式中设置最大字符数限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!