我有一个我编写的 Google Apps Script 脚本,它使用:
paragraph.replaceText(sentences[j], edit);
如果 sentences[j] 以问号结尾,则产生的变化等同于
edit + "?"
例如:
paragraph.replaceText("How are you?", "Hello world!");
将我的文档更改为“Hello World!?”而不是“Hello World!”
这只发生在问号上。我已经用句点、感叹号和省略号对其进行了测试。
我已经尝试了一些事情:
replaceText("?","stuff") 并得到了“?”的无效正则表达式。
replaceText(/\?/, "stuff") 和问号不变。
replaceText(/\?\?/, "?") 不会引发错误,它只是不会更改任何内容。
造句我做
var lines = paragraph.getText().split(/\b(\?|\!|\.\.\.|\u2026|\. \. \.|\.|\n\r|\r\n|\n|\r)/g);
var sentences = [];
for(j=0;j < lines.length;j = j+2){
sentences.push(lines[j]+lines[j+1]);
}
它可以很好地捕获问号。 有人知道如何解决这个问题吗?
最佳答案
搜索模式作为字符串传递,而不是 JavaScript 正则表达式对象。这就是为什么以正则表达式开头的 replaceText 调用不会改变任何内容:
replaceText(/\?/, "stuff"); //and the question marks don't change.
replaceText(/\?\?/, "?");// doesn't throw an error, it just doesn't change anything.
?
本身不是有效的正则表达式(因此出现错误)。
x?
表示零或一个 x,更喜欢一个
如果你不想让?
有特殊意义,你可以转义它。这会工作...
paragraph.replaceText("How are you\?", "Hello world!");
当然,您需要在 sentences
数组中替换所有具有特殊含义的字符。
关于javascript - 使用 Google Apps 脚本 replaceText() 不适用于问号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46261450/