我试图找出一个字符串是否有 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 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.
所以 * 是一个神奇的字符。除非在 [*]
这样的字符类中使用,否则必须转义。
匹配前面正好有 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;
关于regex - 在 Lua 中使用正则表达式查找前导星号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55527349/