简体   繁体   中英

Can someone please explain how the replaceAll function works in the following servlet code from App Engine documentation?

I am not able to understand what text pattern is being replaced in the replaceAll function in the following sample servlet code from App Engine documentation of the Channel API .

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);

Many thanks to anyone who can shed some light on this!!

That code is replacing the text - "{{ token }}" with the value of token in the String index . The braces are escaped because replaceAll() works on regex.

BTW, it can also be done with just replace() . No need of regex here:

index = index.replace("{{ token }}", token);

Deconstructing it:

First, since it's a string, any backslashes in the string have to be escaped. So the string \\\\{\\\\{ token \\\\}\\\\} equates to the regular expression \\{\\{ token \\}\\} .

Okay, so what does that expression do? { is a special character in regular expressions, so the backslashes are there to say that the { should be treated literally as a { character, and the same for } .

So it just looks for the literal string {{ token }} , replacing it with the contents of the token variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM