7

I'm just new to lua... and so I apologize if i'm missing something basic.
i'm running a simple test to see if i can find certain values in a string.

Here's the code:

print(string.find('fd@testca','.') )

Instead of failing, which is what I was expecting, I'm getting back:

mymachinename:/usr/share/std/test# lua test.lua
1       1

Can you tell me where I'm going wrong? Thanks.

dot
  • 14,928
  • 41
  • 110
  • 218

2 Answers2

6

This is because in Lua the find method looks for a pattern, and . represents any character.

You can use character sets to work around the problem:

print(string.find('fd@testca','[.]') )

Here is a link to a small demo.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 2
    It's easier to use `%` as an escape character, similar to the use of backslash in regular expressions: `print(string.find('fd@testca','%.') )` – Keith Thompson Mar 07 '13 at 16:22
  • @KeithThompson That's nice to know, thanks! I'm only a casual user of Lua, so my knowledge is rather limited on the details. – Sergey Kalinichenko Mar 07 '13 at 16:23
  • @KeithThompson I personally think that's a matter of taste. When it comes to escaping symbols like parentheses, I find `[(]` and `[)]` much more readable than `%(` and `%)` - especially when it's interleaved with actual grouping parentheses. Using a character class to escape a single character creates a nice little square that is easily recognizable in a longer pattern, and it also doesn't the "center" of a character (in `%(` the actual information is right of the center of what I'm looking at) - I think that really helps with spotting matching parentheses and the like. – Martin Ender Mar 07 '13 at 22:06
3

Lua uses patterns (described here) to search. You can turn off patterns with the optional fourth parameter:

print(string.find('fd@testca','.', 1, true) )

The optional third parameter (1) is the starting position.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Corey
  • 5,818
  • 2
  • 24
  • 37
  • No, Lua doesn't use regular expressions; it uses *patterns*, [described here](http://www.lua.org/pil/20.2.html) (because the implementation uses much less code). – Keith Thompson Mar 07 '13 at 16:20
  • @KeithThompson: Sorry, I was paraphrasing from the lua-users wiki: "Turn off the regular expression feature by using the optional fourth argument 'plain'." Regardless, the fourth boolean parameter allows for a plain text search. – Corey Mar 07 '13 at 16:27