3

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]?')
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
iGwok
  • 323
  • 5
  • 18

2 Answers2

3

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

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • I like this. Is it not possible to do this in 1 line like in python's regular expressions: "(righteye_RT_%d+ | righteye_RT)" – iGwok Apr 09 '14 at 13:39
  • @iGwok Lua pattern doesn't support `|`, so no, at least not like that. – Yu Hao Apr 09 '14 at 13:45
1

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.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • This works, thanks! But why does this work and %d+? does not? I thought the $ just searches for characters at the end of the string? – iGwok Apr 09 '14 at 13:14
  • `%d+` does not work because it requires at least *one* digit. – lhf Apr 09 '14 at 13:14
  • I see, so %d* will work as well, but the ? was throwing it off as %d*? still does not work. – iGwok Apr 09 '14 at 13:16
  • 1
    @iGwok But be carefull. That pattern matchs `righteye_RT_`string, wich may not be apropriate. – Seagull Apr 09 '14 at 13:16
  • 1
    it does match "righteye_RT_" but also matches "righteye_RT" because of the ? – iGwok Apr 09 '14 at 13:18