【问题标题】:Lua: return content of "{foo}{bar}"Lua:返回“{foo}{bar}”的内容
【发布时间】:2019-03-10 15:40:17
【问题描述】:

对于像"{foo}{bar}" 这样的字符串有一个简单的

str = "{foo}{bar}"
first, second = str:gmatch(...)...

应该给first="foo"second="bar"

问题是foo本身可以有更多的括号,例如:

str = "{foo {baz}{bar}"

这样first = "foo {baz" bar 部分只有字母数字字符,没有括号

【问题讨论】:

  • first, second = str:match('({[^}]*})%s*({[^}]*})') 呢?
  • 对于{foo}{bar},我会得到first="{foo}"second="{bar}",但它应该是first="foo"second="bar",没有外部大括号
  • 我错误地移动了捕获括号:first, second = str:match('{([^}]*)}%s*{([^}]*)}')。见ideone.com/aFroK5
  • 是的,很好:-)。请给它作为答案

标签: string lua pattern-matching lua-patterns


【解决方案1】:

你可以使用

first, second = str:match('{([^}]*)}%s*{([^}]*)}')

Lua demo online

str.match 函数将查找并返回第一个匹配项,由于有两个捕获组,因此在有效匹配项时将返回两个值。

图案的意思:

  • { - 一个 { 字符
  • ([^}]*) - 第 1 组:除 } 之外的任何 0+ 个字符
  • } - 一个 } 字符
  • %s* - 0+ 个空格(不是必需的,但有好处)
  • {([^}]*)} - 同上,只是这里定义了第 2 组。

【讨论】:

  • 在这种情况下,我会得到nilstr = "{Während|see{Was\\_auch\\_immmer}}{17}"。但它应该返回Während|see{Was\\_auch\\_immmer}17。我想左边的括号是问题所在。
  • @Herbert 也许,我在这里想多了。如果您只期望两个值{..},然后是最后一个{},则仅使用str:match('{(.*)}%s*{(.*)}')。见this demo
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 2017-04-03
  • 2017-06-23
相关资源
最近更新 更多