使用正则表达式消除谷歌应用程序脚本中的换行符 [英] Eliminate newlines in google app script using regex
问题描述
我正在尝试为 Google Docs 编写附加组件的一部分,该附加组件使用 replaceText
消除所选文本中的换行符.明显的 text.replaceText("
","");
给出了错误 Invalid argument: searchPattern
.我用 text.replaceText("
","");
得到同样的错误.以下尝试无效: text.replaceText("/
/","");
, text.replaceText("/
/","");
.我不知道为什么 Google App Script 不允许识别正则表达式中的换行符.
I'm trying to write part of an add-on for Google Docs that eliminates newlines within selected text using replaceText
. The obvious text.replaceText("
","");
gives the error Invalid argument: searchPattern
. I get the same error with text.replaceText("
","");
. The following attempts do nothing: text.replaceText("/
/","");
, text.replaceText("/
/","");
. I don't know why Google App Script does not allow for the recognition of newlines in regex.
我知道已经有一个附加组件可以执行此操作,但我想将此功能合并到我的附加组件中.
I am aware that there is an add-on that does this already, but I want to incorporate this function into my add-on.
即使是基本的也会出现这个错误
This error occurs even with the basic
DocumentApp.getActiveDocument().getBody().textReplace("
","");
我的全部功能:
function removeLineBreaks() {
var selection = DocumentApp.getActiveDocument().getSelection();
if (selection) {
var elements = selection.getRangeElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
// Only deal with text elements
if (element.getElement().editAsText) {
var text = element.getElement().editAsText();
if (element.isPartial()) {
text.replaceText("
","");
}
// Deal with fully selected text
else {
text.replaceText("
","");
}
}
}
}
// No text selected
else {
DocumentApp.getUi().alert('No text selected. Please select some text and try again.');
}
}
推荐答案
似乎在 replaceText
中,要删除使用 Shift-ENTER<输入的软回车,你可以使用 v
:
It seems that in replaceText
, to remove soft returns entered with Shift-ENTER, you can use v
:
.replaceText("\v+", "")
如果您想删除所有其他"控制字符(C0、DEL 和 C1 控制代码),您可以使用
If you want to remove all "other" control characters (C0, DEL and C1 control codes), you may use
.replaceText("\p{Cc}+", "")
请注意,v
模式是 JavaScript 正则表达式引擎支持的一种结构,被认为匹配一个 垂直制表符 (≡