|
string finding a whole word only?
|
Reply to this subject
Start a new subject
 
Refresh page
| Posted by |
Rivius
(93 posts) bio
|
| Date |
Fri 06 May 2011 05:56 PM (UTC) [ quote
] |
| Message |
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? | top |
|
| Posted by |
Twisol
USA (2,230 posts) bio
|
| Date |
Reply #1 on Fri 06 May 2011 06:27 PM (UTC) [ quote
] |
| Message |
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 |
'Soludra' on Achaea
Blog: http://jonathan.com/
GitHub: http://github.com/Twisol | top |
|
| Posted by |
Fiendish
USA (851 posts) bio
Global Moderator |
| Date |
Reply #2 on Fri 06 May 2011 08:15 PM (UTC) [ quote
] |
| Message |
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 |
http://aardwolfclientpackage.googlecode.com/ | top |
|
| Posted by |
Nick Gammon
Australia (18,800 posts) bio
Forum Administrator |
| Date |
Reply #3 on Fri 06 May 2011 10:26 PM (UTC) [ quote
] |
| Message |
Also see:
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. |
- Nick Gammon
www.gammon.com.au, www.mushclient.com | top |
|
The dates and times for posts above are shown in Universal Co-ordinated Time (UTC).
To show them in your local time you can join the forum, and then set the 'time correction' field in your profile to the number of hours difference between your location and UTC time.
1,897 views.
Reply to this subject
Start a new subject
 
Refresh page
top
Comments to:
Gammon Software support
Forum RSS feed ( http://www.gammon.com.au/rss/forum.xml )