1

我有一个字符串hello /world today/

我需要替换/world today//MY NEW STRING/

阅读我发现的手册

newString = string.match("hello /world today/","%b//")

我可以用 withgsub替换,但我想知道是否还有一种优雅的方式来返回 之间的文本/,我知道我可以修剪它,但我想知道是否有模式。

4

1 回答 1

2

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.

于 2010-09-03T08:38:44.770 回答