在 Lua 中使用正则表达式查找前导星号

Look for leading asterisks using regex in Lua

我想知道字符串是否有 06 个前导星号 例如 如果字符串有“******abc”则通过 如果字符串有“*abc”或“**abc”或“*”则失败

我已经在线试过了 (https://www.lua.org/cgi-bin/demo)

s1 = "**"

if (string.match(s1, '^****$')) then
 print "pattern matches"
else
 print "pattern does not match"
end

不过好像不行。

Lua 没有正则表达式,因为它是轻量级的。但是,下面的模式与您要完成的目标相符。

s1 = "*******TEST"

if (string.match(s1, '^[*][*][*][*][*][*]')) then
 print "pattern matches"
else
 print "pattern does not match"
end

来自Lua Reference Manual 6.4.1 Patterns:

Character Class: A character class is used to represent a set of characters. The following combinations are allowed in describing a character class:

x: (where x is not one of the magic characters ^$()%.[]*+-?) represents the character x itself.

...

%x: (where x is any non-alphanumeric character) represents the character x. This is the standard way to escape the magic characters.

所以*是一个神奇的字符。除非在字符 class 中使用,否则必须转义,例如 [*].

匹配前面正好有 6 个星号的任何字符串的模式是 "^%*%*%*%*%*%*[^*]+"

[^*]+ 确保您剩余的字符串不包含其他星号。通过匹配至少一个非星号字符。

[^set]: represents the complement of set, where set is interpreted as above.

...

a single character class followed by '+', which matches one or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;