string finding a whole word only?

Posted by Rivius on Fri 06 May 2011 05:56 PM — 4 posts, 24,609 views.

#0
I was wondering what the regex syntax would be for finding a word would look like.

For example:

string.find("banana bananapeel", "banana")

returns true on both banana and bananapeel. However, I want it to strictly match just the word "banana". How would I do this?
USA #1
Lua's built-in pattern matching library doesn't really have a word-border match, but PCRE does:
local re = rex.new("\bbanana\b")
-- re can be created once and used many times
local s, e, matches = re:match("banana bananapeel")


http://www.gammon.com.au/forum/?id=4905
USA Global Moderator #2
Lua can do anything!


my_string = "bananaphone banana"
find_me = "banana"
start,finish = string.find(string.gsub(my_string,"(.*)"," %1 "), "[^%a]"..find_me.."[^%a]")
finish = finish-2


:D
Australia Forum Administrator #3
Also see:

Template:post=6034
Please see the forum thread: http://gammon.com.au/forum/?id=6034.


Scroll down to near the bottom about the "frontier pattern". That does exactly what you want, because it detects the transition between letters and non-letters.