【问题标题】:Replace string with condition in google script用谷歌脚本中的条件替换字符串
【发布时间】:2023-04-01 07:42:01
【问题描述】:

在谷歌脚本中,我试图根据它后面的字符替换%string。

我尝试过使用:

var indexOfPercent = newString.indexOf("%"); 

然后检查indexOfPercent+1的字符,但indexOf只返回第一次出现的'%'。

如何获得所有事件?也许有更简单的方法(正则表达式)?


编辑:

最后,我想将所有出现的% 替换为%%,但如果百分号是%@%@ 的一部分,则不是。

总结一下:我的字符串:Test%@ Test2%s Test3%. 应该是:Test%@ Test2%s Test3%%.

我试过用这样的东西:

  //?!n Matches any string that is not followed by a specific string n
  //(x|y)   Find any of the alternatives specified
  var newString = newString.replace(\%?![s]|\%?![%], "%%")

但它没有找到任何字符串。我不熟悉正则表达式,所以也许这是一个简单的错误。

谢谢

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    试试这个代码:

    // replace all '%'
    var StrPercent = '%100%ffff%';
    var StrNoPersent = StrPercent.replace(/\%/g,'');
    Logger.log(StrNoPersent); // 100ffff
    

    寻找more info here


    编辑

    在您的情况下,您需要正则表达式,其中的字符不跟一组字符。在这里提出了类似的问题:

    Regular expressions - how to match the character '<' not followed by ('a' or 'em' or 'strong')?

    你的代码:

    function RegexNotFollowedBy() {
    
    var sample = ['Test%@',
                  'Test2%s',
                  'Test3%',
                  '%Test4%'];
    
    var RegEx = /%(?!s|@)/g;
    var Replace = "%%";
    
    var str, newStr;
    
      for (var i = 0; i < sample.length; i++) {
          str = sample[i];
          newStr = str.replace(RegEx, Replace);
          Logger.log(newStr);
    
      }
    
    }
    

    我会解释表达式/%(?!s|@)/g

    • % -- 看'%'
    • (text1|text2|text3...|textN) -- 后面没有 text1、2 等。
    • g -- 查找搜索文本的准确性

    【讨论】:

    • 非常感谢。它确实解决了查找所有出现的 % 符号的问题,但我仍然想使用正则表达式来检查以下字符的条件。查看编辑。
    • 我已经添加了答案。
    猜你喜欢
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 2014-09-30
    • 2014-11-24
    • 1970-01-01
    相关资源
    最近更新 更多