【问题标题】:Finding all the {param} in a string查找字符串中的所有 {param}
【发布时间】:2017-01-05 14:15:35
【问题描述】:

我的字符串有占位符,格式总是 {text}

例如:

The {adjective} brown {animal} {action}s over the lazy {secondanimal}!

我希望有一个字符串数组["{adjective}","{animal}","{action}","{secondanimal}"]

我希望避免编写如下所示的解决方案:

Look for '{' then look for '}' then take substring.

使用正则表达式或 LINQ 可能更直接的方法是什么?我注意到了 Split 方法,但我不仅有一个分隔符。

【问题讨论】:

    标签: c# regex string parsing


    【解决方案1】:

    假设您的 {param} 元素仅包含单词字符,我将使用 {[\w]+} 来匹配它们。

    string input = "The {adjective} brown {animal} {action}s over the lazy {secondanimal}!";
    string[] result = Regex.Matches(input, @"{[\w]+}").Cast<Match>().Select(x => x.Value).ToArray();
    

    {param} 的定义有点宽泛。对于此示例,您还可以使用 {[a-z]+}。

    注意,这种方法不适用于嵌套的{param}。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 2012-10-12
      • 1970-01-01
      相关资源
      最近更新 更多