Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

replaceAll method  RSS feed

 
Chris Yates
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I saw this line of code to parse a calculation giving as a String such as "15+15".
i

Can someone explain what it does in detail?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first argument to replaceAll is a regular expression - a pattern that consists of rules that determine how to find a piece of text that matches the pattern.

The pattern ([-+*/]) means: one of the characters -, +, * or /

The call in your example replaces each -, +, * or / by " $1 ". So if input would be "15+15" then the result of the call would be "15 $1 15".

It's followed by a call to split the resulting string on spaces, so you'd end up with a String[] containing three strings: "15", "$1", "15".
 
Paweł Baczyński
Bartender
Posts: 2054
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, the result will be:
"15", "+", "15"

javadoc wrote:Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string
 
Stephan van Hulst
Saloon Keeper
Posts: 7806
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, the second argument is a so called "replacement string". The dollar sign is used to reference capturing groups in the regular expression. "$1" refers to group 1; in this case the replaceAll() call is used to put spaces around the operators -, +, * and /.

The result of evaluating the expression for the string "15+15" would be {"15", "+", "15"}.
 
Chris Yates
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's pretty cool, thanks!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!