Match if something is not preceded by something else
I'm trying to parse a string and extract some numbers from it. Basically, any 2-3 digits should be matched, except the ones that have "TEST" before them. Here are some examples:
TEST2XX_R_00.01.211_TEST => 00, 01, 211
TEST850_F_11.22.333_TEST => 11, 22, 333
TESTXXX_X_12.34.456 => 12, 34, 456
Here are some of the things I've tried:
(?<!TEST)[0-9]{2,3}
- ignores only the first digit after TEST
_[0-9]{2,3}|.[0-9]{2,3}
- matches the numbers correctly, but matches the character before them (_ or .) as well.
I know this might be a duplicate to regex for matching something if it is not preceded by something else but I could not get my answer there.
Unfortunately, there is no way to use a single pattern to match a string not preceded with some sequence in Lua (note that you can't even rely on capturing an alternative that you need since TEST%d+|(%d+)
will not work in Lua, Lua patterns do not support alternation).
You may remove all substrings that start with TEST
+ digits after it, and then extract digit chunks:
local s = "TEST2XX_R_00.01.211_TEST"
for x in string.gmatch(s:gsub("TEST%d+",""), "%d+") do
print(x)
end
See the Lua demo
Here, s:gsub("TEST%d+","")
will remove TEST<digits>+
and %d+
pattern used with string.gmatch
will extract all digit chunks that remain.
下一篇: 如果某件事没有其他事情发生,就匹配