Reputation: 333
I understand that I should be using string.match()
to do this but I am having trouble matching characters that "might" be in the string, for example:
teststring = "right_RT_12"
I can easily do something like:
string.match(teststring , 'righteye_RT_[0-9]+')
This is fine if there is always "_[0-9]+ on the end of the test string, but there might be an instance where there are no digits on the end. How would I cater for that in Lua?
In Python I could do something like:
re.search("righteye_RT(_[0-9]+)?", teststring)
I thought something like this would work:
string.match(teststring, 'righteye_RT_?[0-9]+?')
but it did not. the result = nil
However, the following does work, but only finds the 1st digit:
string.match(teststring, 'righteye_RT_?[0-9]?')
Upvotes: 3
Views: 71
Reputation: 122383
?
can be used only on one character in Lua pattern. You can use or
to match two patterns:
local result = string.match(teststring , 'righteye_RT_%d+')
or string.match(teststring , 'righteye_RT')
Note that or
operator is short-circuit. So it try to match the first pattern first, if and only if it fails (returns nil
), it would try to match the second pattern.
Upvotes: 3
Reputation: 72312
Try this:
string.match(teststring, 'righteye_RT_?%d*$')
Note the end-of-string anchor $
. Without it, %d*
matches the empty string and so the whole pattern would match things like righteye_RT_junk
.
Upvotes: 1