繁体   English   中英

使用正则表达式在 Google Sheets 应用脚本中查找替换不起作用

[英]Find Replace In Google Sheets App Scripts With Regex Not Working

我在 SO 上阅读了很多关于此的帖子。 我在 google 脚本中使用 Regex 时遇到问题。

我有一个域列表。

目标:我想从列表中的每个域中删除所有路径信息( .*/之后的所有内容)

例如,我想转这个:

example.com/path-after-domain

example2.com/another-path-afterDomain

进入这个:

example1.com

example2.com

这是我想要做的。

循环替换function

function replaceInSheet(values, to_replace, replace_with) {
  
  for(var row in values){
 
  var replaced_values = values[row].map(function(original_value) {
    return original_value.toString().replace(to_replace,replace_with)
  })
}
}

通过传递正则表达式使用 function

replaceInSheet(values, '((\/\w+)*\/)(.*)', "")

我还使用createtextfinder进行了测试。 但是尝试使用正则表达式时出现错误

const check = range.createTextFinder("((\/\w+)*\/)(.*)").useRegularExpression(true)

check.replaceWith("")

注意 - 我用https://regex101.com/测试了正则表达式,它成功获取了所有路径信息

我相信你的目标如下。

  • 您想使用 Google Apps 脚本实现以下转换。

    •  example.com/path-after-domain, example2.com/another-path-afterDomain
    •  example1.com, example2.com

在这种情况下,如何使用split如下?

示例脚本:

 const values = ["example.com/path-after-domain", "example2.com/another-path-afterDomain"]; const res = values.map(e => e.split("/")[0]); console.log(res) // [ 'example.com', 'example2.com' ]

笔记:

  • 如果您想将此用作自定义 function,以下示例脚本怎么样? 在这种情况下,请将自定义 function 像=SAMPLE(A1:A10)放到一个单元格中。

     const SAMPLE = values => values.map(r => r.map(c => c.split("/")[0]));
  • 如果您想使用((\/\w+)*\/)(.*)的正则表达式来使用 TextFinder,那么下面的示例脚本怎么样? 在这种情况下,请转义\ 我认为\\/.*可能也可以使用。

     const sheet = SpreadsheetApp.getActiveSheet(); sheet.getRange("A1:A" + sheet.getLastRow()).createTextFinder("((\\/\\w+)*\\/)(.*)").useRegularExpression(true).replaceAllWith("");
    • 在这种情况下,使用列“A”。
  • 如果使用内置的 function,下面的示例公式怎么样?

     =ARRAYFORMULA(IFERROR(INDEX(SPLIT(A1:A,"/"),, 1))) =ARRAYFORMULA(REGEXREPLACE(A1:A,"/.*",""))

参考:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM