[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Patterns that cope with beginnings and end of strings
- From: Geoff Leyland <geoff_leyland@...>
- Date: Fri, 2 Aug 2013 12:12:07 +1200
Hi,
I think I must have missed something fundamental with patterns - I keep having trouble with beginnings and ends of strings. Suppose I have the nonsense string "all all ball all" and I'd like to change all the "all"s (but not the ball) to "none".
This requires detecting either a space or the start of a string before "all" or a space or the end of a string after "all". I'd guess I'd like to write the patterns [ ^] and [ $], but they don't work.
I can detect the end of a string or a space with "%f[%s%z]", but I can't work out how to detect the beginning of a string or a space.
I must be missing something obvious. Any pointers?
Cheers,
Geoff
$ lua
Lua 5.1.5 Copyright (C) 1994-2012 Lua.org, PUC-Rio
> =("all all ball all"):gsub("all", "none")
none none bnone none 4
> =("all all ball all"):gsub("(%s)all(%s)", "%1none%2")
all none ball all 1
> =("all all ball all"):gsub("([ ^])all([ $])", "%1none%2")
all none ball all 1
> =("all all ball all"):gsub("%f[%S]all%f[%s]", "none")
all none ball all 1
> =("all all ball all"):gsub("%f[%S]all%f[%s%z]", "none")
all none ball none 2
> return ("all all ball all"):gsub("%f[%S]all%z", "none")
all all ball all 0