Google Apps脚本/Javascript搜索并用正则表达式替换不起作用 [英] Google Apps Script/Javascript search and replace with regex not working
问题描述
我知道那里有很多类似的问题和答案,但是我没有运气.
I know there are many similar questions and answers out there but I have had no luck.
我只是想在Google文档上运行一个正则表达式,并用大写字母替换它.我有一个有效的正则表达式,一个简单的字符串替换也可以,但是我无法使用任何形式的正则表达式.我在做什么错了?
I simply want to run a regex on a Google Doc and have it replace what it finds with Uppercase. I have a working regular expression, and a simple string replace works, but I can't get a regex of any kind to work. What am I doing wrong?
function searchAndReplace() {
var bodyElement = DocumentApp.getActiveDocument().getBody();
var regExp = new RegExp(/[\n][\n]([^\n]+)[\n][^\n|\s]/gim);
bodyElement.replaceText(regExp, '$1'.toUpperCase());
}
推荐答案
As shown in the replaceText documentation, it expects a string
on both parameters. The first one will automatically generate a RegExp
for you. Therefore you can use a regular expression, but due to this syntax limitation, you can not pass RegExp
flags to it (in your example the gim
).
此外,由于第二个参数也只接受字符串,因此您无法通知函数,这是您需要编写适当的toUpperCase
的原因(即使使用内置的javascript,在您的示例中也是错误的) string.replace 函数).
Also, since the second parameter also only accepts a string, you can not inform a function, which is what you'd need to make a proper toUpperCase
(which is wrong in your example even if using javascript built-in string.replace function).
从我刚进行的测试中,使用"$&"替换字符串模式或"$#"也不起作用.
And from tests I just made, replacement string patterns using "$&" or "$#" don't work either.
因此,要实现所需的功能,您必须自己实施搜索和替换操作(可能使用
So, to achieve what you're looking for you'll have to implement this search-and-replace yourself (possibly using findText to help on the "search" part).
这篇关于Google Apps脚本/Javascript搜索并用正则表达式替换不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!