problems using replaceText for special characters:

2019-06-03 17:02发布

I want to replace "\cite{foo123a}" with "[1]" and backwards. So far I was able to replace text with the following command

body.replaceText('.cite{foo}', '[1]');

but I did not manage to use

body.replaceText('\cite{foo}', '[1]');
body.replaceText('\\cite{foo}', '[1]');

Why?

The back conversion I cannot get to work at all

body.replaceText('[1]', '\\cite{foo}');

this will replace only the "1" not the [ ], this means the [] are interpreted as regex character set, escaping them will not help

body.replaceText('\[1\]', '\\cite{foo}');//no effect, still a char set
body.replaceText('/\[1\]/', '\\cite{foo}');//no matches

The documentation states

A subset of the JavaScript regular expression features are not fully supported, such as capture groups and mode modifiers.

Can I find a full description of what is supported and what not somewhere?

1条回答
小情绪 Triste *
2楼-- · 2019-06-03 18:00

I'm not familiar with Google Apps Script, but this looks like ordinary regular expression troubles.

Your second conversion is not working because the string literal '\[1\]' is just the same as '[1]'. You want to quote the text \[1\] as a string literal, which means '\\[1\\]'. Slashes inside of a string literal have no relevant meaning; in that case you have written a pattern which matches the text /1/.

Your first conversion is not working because {...} denotes a quantifier, not literal braces, so you need \\\\cite\\{foo\\}. (The four backslashes are because to match a literal \ in a regular expression is \\, and to make that a string literal it is \\\\ — two escaped backslashes.)

查看更多
登录 后发表回答