tags:

views:

33

answers:

1

I have a string like "hello /world today/"

I need to replace /world today/ with /MY NEW STRING/

Reading the manual I have found newString = string.match("hello /world today/","%b//") which I can use with gsub to replace, but I wondered is there also an elegant way to return just the text between the '/', I know I could just trim it, but I wondered if there was a pattern.

Thanks in advance, from a new Lua user.

+1  A: 

Try something like one of the following:

  • slashed_text = string.match("hello /world today/", "/([^/]*)/")
  • slashed_text = string.match("hello /world today/", "/(.-)/")
  • slashed_text = string.match("hello /world today/", "/(.*)/")

This works because string.match returns any captures from the pattern, or the entire matched text if there are no captures. The key then is to make sure that the pattern has the right amount of greediness, remembering that Lua patterns are not a complete regular expression language.

The first two should match the same texts. In the first, I've expressly required that the pattern match as many non-slashes as possible. The second (thanks lhf) matches the shortest span of any characters at all followed by a slash. The third is greedier, it matches the longest span of characters that can still be followed by a slash.

The %b// in the original question doesn't have any advantages over /.-/ since the the two delimiters are the same character.

Edit: Added a pattern suggested by lhf, and more explanations.

RBerteig
Thanks I will give that a go.
Jane T
You probably want `"/(.-)/"` instead of `"/(.*)/"`.
lhf