Search code examples
stringlualua-patterns

Pattern for characters that might be in the string


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]?')

Solution

  • 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.