开发者

Lua Pattern for extracting/replacing value in / /

开发者 https://www.devze.com 2023-01-14 02:08 出处:网络
I have a string like hello /world today/ I need to replace /world today/ with /MY NEW STRING/ Reading th开发者_开发知识库e manual I have found

I have a string like hello /world today/

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

Reading th开发者_开发知识库e 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消