Google Apps Script正则替换直引号为智能引号并保留格式的方法
解决Google Apps Script替换智能引号并保留格式的问题
你的原脚本问题出在直接提取纯文本替换,会丢失所有格式。要实现保留格式的智能引号替换,需要逐个处理文档中的文本匹配项,复制原格式后再替换字符。
可行脚本
function convertToSmartQuotes() { const doc = DocumentApp.getActiveDocument(); const body = doc.getBody(); // 替换左智能引号:匹配行首/空白后的直引号,后跟非空白字符 const leftQuoteRegex = "(?<=^|[ \\t])\"(?=\\S)"; processMatches(body, leftQuoteRegex, "“"); // 替换右智能引号:匹配非空白字符后的直引号,后跟空白/行尾 const rightQuoteRegex = "(?<=\\S)\"(?=[ \\t]|$)"; processMatches(body, rightQuoteRegex, "”"); } function processMatches(element, regexPattern, replacement) { // 处理文本元素 if (element.getType() === DocumentApp.ElementType.TEXT) { let match = element.findText(regexPattern); while (match) { const textEl = match.getElement().asText(); const start = match.getStartOffset(); const end = match.getEndOffsetInclusive(); // 保存原位置的格式 const format = { bold: textEl.isBold(start), italic: textEl.isItalic(start), underline: textEl.isUnderline(start), fgColor: textEl.getForegroundColor(start), bgColor: textEl.getBackgroundColor(start), fontSize: textEl.getFontSize(start), fontFamily: textEl.getFontFamily(start) }; // 替换字符 textEl.deleteText(start, end); textEl.insertText(start, replacement); // 恢复格式 textEl.setBold(start, start, format.bold); textEl.setItalic(start, start, format.italic); textEl.setUnderline(start, start, format.underline); textEl.setForegroundColor(start, start, format.fgColor); textEl.setBackgroundColor(start, start, format.bgColor); textEl.setFontSize(start, start, format.fontSize); textEl.setFontFamily(start, start, format.fontFamily); // 查找下一个匹配 match = element.findText(regexPattern, match); } } else { // 递归处理子元素(如表格、列表、文本框) const children = element.getChildren(); while (children.hasNext()) { processMatches(children.next(), regexPattern, replacement); } } }
关键说明
- 避免格式丢失:不再提取纯文本,而是直接操作文档中的文本元素,逐个处理匹配的引号,先保存原位置的格式,替换后再恢复。
- 正则匹配逻辑:
- 左智能引号:确保是段落开头或空白后的引号,且后面紧跟有效内容,避免误替换
- 右智能引号:确保是内容后的引号,后面是空白或段落结尾,区分左右引号
- 全文档覆盖:递归处理所有子元素,包括表格、列表项、文本框等嵌套内容,确保整个文档的引号都被替换。
内容的提问来源于stack exchange,提问作者Connor
相关产品推荐
相关产品推荐

