regex - 准确匹配 Google Apps 脚本中的两个连续空格
问题描述
我正在尝试使用精确匹配两个连续的空格DocumentApp.getActiveDocument().getBody().replaceText()
并将它们替换为单个空格。
不幸的是,它只支持一些正则表达式(https://github.com/google/re2/wiki/Syntax)。
我已经尝试过DocumentApp.getActiveDocument().getBody().replaceText("[^ ] {2}[^ ]", " ")
,但这也与文本周围的字符相匹配。
我已经尝试过DocumentApp.getActiveDocument().getBody().replaceText("([^ ]) {2}([^ ])", "$1 $2")
,但这会输出“$1 $2”而不是“字符 字符”
我已经尝试过DocumentApp.getActiveDocument().getBody().replaceText(" {2}", " ")
,但这也匹配更大空间组中的两个空间。
解决方案
(对我来说)很难为所需的替换编写一个正则表达式,因为每次也替换周围的字符(非空格)。此外,在一般情况下,当空格位置位于字符串的开头或结尾时,我们应该考虑特殊情况。
因此,我建议以下各种替换的 2 个函数:
function replaceDoubleSpace() {
var body = DocumentApp.getActiveDocument().getBody();
var count = replaceWithPattern('^ $', body);
Logger.log(count + ' replacement(s) done for the entire string');
count = replaceWithPattern('[^ ]{1} [^ ]{1}', body);
Logger.log(count + ' replacement(s) done inside the string');
count = replaceWithPattern('^ [^ ]{1}', body);
Logger.log(count + ' replacement(s) done at the beginning of the string');
count = replaceWithPattern('[^ ]{1} $', body);
Logger.log(count + ' replacement(s) done at the end of the string');
}
function replaceWithPattern(pat, body) {
var patterns = [];
var count = 0;
while (true) {
var range = body.findText(pat);
if (range == null) break;
var text = range.getElement().asText().getText();
var pos = range.getStartOffset() + 1;
text = text.substring(0, pos) + text.substring(pos + 1);
range.getElement().asText().setText(text);
count++;
}
return count;
}
当然,第一个函数可能会被简化,但在这种情况下它变得不太可读:
function replaceDoubleSpace() {
var body = DocumentApp.getActiveDocument().getBody();
var count = replaceWithPattern('^ $|[^ ]{1} [^ ]{1}|^ [^ ]{1}|[^ ]{1} $', body);
Logger.log(count + ' replacement(s) done');
}
推荐阅读
- reactjs - 裁剪图像后,图像下载为 .png
- angular - 来自 Firestore 的完整日历事件数据未显示
- javascript - SheetJS readFile的进度条读取大型excel文件
- html - 修复输入字段内提交按钮的响应位置
- javascript - Stripe - 付款通过但在此处出现错误“没有这样的 payment_intent:pm_1Gyj0uD3zt5RrIg0lSfDPKOO”
- c# - AlarmManager 在睡眠模式下不触发
- python - 如何在 PANDAS 中为 2 索引设置条件
- swift - 致命错误:在实例化 NSTextView 的子类时使用未实现的初始化程序 'init(frame:textContainer:)
- python - 在新函数中调用前一个函数
- html - 我应该使用哪些工具来获得网站所有权?