lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I have to change a whole word (s) with another word (sh) in a string
(line), using gsub, but I can't find a simple way to do it.

Suppose the first word (s) is "the"; I want to change every occurrence of
"the" but not to change the "the" in "theory", "atheist" or "lithe".

So far, the only way I found is this, but it seems a bit ridicolous:

  line = gsub(line, '(%W)'..s..'(%W)', '%1'..sh..'%2') -- in the middle
  line = gsub(line, '^'..s..'(%W)', sh..'%1') -- start of line
  line = gsub(line, '(%W)'..s..'$', '%1'..sh) -- end of line
  line = gsub(line, '^'..s..'$', sh) -- alone on the line

My problem comes from the lack of a "word boundary" magic character in
patterns (like "\b" in Perl). "%W" requires an existing character in that
position, so it doesn't seem to work at the beginning or at the end of a
string, and ^$ anchors can't be used in [character sets].

I suppose I am doing something wrong; is there a simpler way and I missed
something obvious?

  Enrico