[英]Can someone please explain how the replaceAll function works in the following servlet code from App Engine documentation?
我无法理解Channel API的App Engine文档中的以下示例servlet代码中的replaceAll函数中正在替换的文本模式。
String token = channelService.createChannel(game.getChannelKey(userId));
// Index is the contents of our index.html resource, details omitted for brevity.
index = index.replaceAll("\\{\\{ token \\}\\}", token);
非常感谢任何能够对此有所了解的人!
该代码正在使用String index
的token
值替换文本 - "{{ token }}"
。 大括号是转义的,因为replaceAll()
适用于正则表达式。
顺便说一句,它也可以只replace()
来完成。 这里不需要正则表达式:
index = index.replace("{{ token }}", token);
解构它:
首先,因为它是一个字符串,所以字符串中的任何反斜杠都必须被转义。 因此字符串 \\\\{\\\\{ token \\\\}\\\\}
等同于正则表达式 \\{\\{ token \\}\\}
。
好的,那表达式是做什么的? {
是在正则表达式特殊字符,因此反斜杠在那里说, {
应该从字面上视为{
字符,与同为}
。
所以它只查找文字字符串{{ token }}
,将其替换为token
变量的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.