【问题标题】:How to replace part of string BEHIND search criteria in Jsonnet string?如何替换 Jsonnet 字符串中的部分字符串 BEHIND 搜索条件?
【发布时间】:2021-11-05 11:58:54
【问题描述】:

我正在寻找与 std.strReplace(str, from, to) 等效的方法来替换 Jsonnet 中的部分字符串。我需要from 更像一个“模式”,类似于s/key="[^"]*"/key="myNewValue"/g,所以实际上我正在寻找的是一个正则表达式搜索和替换。

编辑: 好的,这可能会帮助我解决我的具体问题:

local replaceKey(string) = (
  local replaceNext = false;
  std.join('"', [
  if std.endsWith(x, "key=") then
    replaceNext = true;
    x
  else if replaceNext then
    replaceNext = false;
    "myNewValue"
  else
    x
  for x in  std.split(string, '"')
  ])
);

但是“为先前定义的局部变量设置一个新值”(replaceNext = true;)将不起作用。

Not a binary operator: =

有什么办法吗?

【问题讨论】:

    标签: jsonnet


    【解决方案1】:

    Jsonnet 目前不支持正则表达式,一些参考:

    【讨论】:

      【解决方案2】:

      我现在有以下解决方案:

      local modifyElement(element, newValue) =
        std.join('"', std.mapWithIndex(                                                             
          function(i, str)
            if i == 1 then
              newValue
            else
              str,
          std.split(element, '"')
        ));
      
      local splitSubstring(string, pattern) = (
        local indexes = [0] + std.findSubstr(pattern, string);
        local lenIdx = std.length(indexes);
        local lenStr = std.length(string);
        std.mapWithIndex(
          function(i, strIndex)
            std.substr(string, strIndex, 
              if lenIdx > i+1 then indexes[i+1]-strIndex
              else lenStr-strIndex),
          indexes
        )
      );
      
      local replaceValue(string, searchKey, newValue) = 
        std.join("", std.mapWithIndex(
            function(index, element)
              if index == 0 then
                element
              else
                modifyElement(element, newValue),
          splitSubstring(string, searchKey)));
      
      
      // TESTCASE
      
      local oldExpression = 'rate(kube_pod_container_status_restarts_total{namespace=~"^(ns1|ns2)$",job="expose-kubernetes-metrics"}[10m]) * 60 * 5 > 0';
      {'test': replaceValue(oldExpression, "namespace=~", "^myspaces-.*$")}
      

      但是,如果这可能更容易实现,我会很感兴趣,因为对于这样一个微不足道的任务来说,这实在是太疯狂了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-13
        • 2015-05-02
        • 1970-01-01
        • 2016-12-08
        • 2016-01-19
        • 1970-01-01
        • 1970-01-01
        • 2020-01-06
        相关资源
        最近更新 更多