Scala replace " by \" - scala

How to replace the double quote by \":
val s = """I am "groot"."""
so the output will be """I am \"groot\"."""
I tried with but no luck
s.replaceAll('"', '\"')

So #Tanjin provides the correct solution. However, the reason your solution does not work is this.
s.replaceAll('"', '\"')
Backslashes have special meaning in string and character literals, so '\"' compiles down to just the quote character. Running in the REPL will show you this
scala> '\"'
res2: Char = "
Meanwhile, using triple-quote strings disables this behavior.
scala> """\""""
res3: String = \"

Try this way:
s.replaceAll("\"", "\\\\\"")

How does this work:
s.replace(""""""", """\"""")

Related

Running a PowerShell script file with path containing spaces from Jenkins Pipeline without using backtick

I want to run the following PowerShell script file from Jenkins Pipeline:
".\Folder With Spaces\script.ps1"
I have been able to do it with the following step definition:
powershell(script: '.\\Folder` With` Spaces\\script.ps1')
So I have to remember to:
escape the backslash with a double backslash (Groovy syntax)
escape the space with backtick (PowerShell syntax)
I would prefer to avoid at least some of this. Is it possible to avoid using the backtick escaping, for example? (Putting it between "" does not seem to work, for some reason.)
I found that it's possible to use the ampersand, or invoke, operator, like this:
powershell(script: "& '.\\Folder With Spaces\\script.ps1'")
That gets rid of the backtick escaping, and should make life a tiny bit easier.
To avoid escaping the backslashes you could use slashy strings or dollar slashy strings as follows. However you cannot use a backslash as the very last character in slashy strings as it would escape the /. Of course slashes as well would have to be escaped when using slashy strings.
String slashy = /String with \ /
echo slashy
assert slashy == 'String with \\ '
// won't work
// String slashy = /String with \/
String dollarSlashy = $/String with / and \/$
echo dollarSlashy
assert dollarSlashy == 'String with / and \\'
And of course you'll lose the possibility to include newlines \n and other special characters in the string using the \. However as both slashy and dollar slashy strings have multi line support at least newlines can be included like:
String slashyWithNewline = /String with \/ and \
with newline/
echo slashyWithNewline
assert slashyWithNewline == 'String with / and \\ \nwith newline'
String dollarSlashyWithNewline = $/String with / and \
with newline/$
echo dollarSlashyWithNewline
assert dollarSlashyWithNewline == 'String with / and \\ \nwith newline'
If you combine that with your very own answer you won't need both of the escaping.

Scala string formating exercises error: not compiling

I am working on the exercises from https://www.scala-exercises.org/std_lib/formatting
For the following question, m answer seems incorrect but I do not know why.
val c = 'a' //unicode for a
val d = '\141' //octal for a
val e = '\"'
val f = '\\'
"%c".format(c) should be("a") //my answers
"%c".format(d) should be("a")
"%c".format(e) should be(")
"%c".format(f) should be(\)
your answer should be enclosed in quotes
"%c".format(e) should be("\"")
"%c".format(f) should be("\\")
because it wouldn't recognize string unless it's enclosed in quotes
Your last two lines are invalid Scala code and cannot be compiled:
// These are wrong
"%c".format(e) should be(")
"%c".format(f) should be(\)
The be() function needs to be passed a String, and neither of those calls are being passed a String. A String needs to start and end with a double-quote (there are some exceptions).
// In this case you started a String with a double-quote, but you are never
// closing the string with a second double-quote
"%c".format(e) should be(")
// In this case you are missing both double-quotes
"%c".format(f) should be(\)
In this case the code should be:
"%c".format(e) should be("\"")
"%c".format(f) should be("\\")
If you want a character to be treated literally in a String, you need to "escape" it with a backslash. So if you want to literally show a double-quote, you need to prefix it with a backslash:
\"
And as a String:
"\""
Similarily for a backslash:
\\
As a String:
"\\"
Using an IDE makes this easier to see. Using IntelliJ the String is green but the special non-literal characters are highlighted in orange.
Check quote signs.
https://www.tutorialspoint.com/scala/scala_strings.htm
https://docs.scala-lang.org/overviews/core/string-interpolation.html
https://learnxinyminutes.com/docs/scala/
You can run Scala code online and check yourself here:
https://scastie.scala-lang.org
https://ideone.com/

Scala - write Windows file paths that contain spaces as string literals

I need to make some Windows file paths that contain spaces into string literals in Scala. I have tried wrapping the entire path in double quotes AND wrapping the entire path in double quotes with each directory name that has a space with single quotes. Now it is wanting an escape character for "\Jun" in both places and I don't know why.
Here are the strings:
val input = "R:\'Unclaimed Property'\'CT State'\2015\Jun\ct_finderlist_2015.pdf"
val output = "R:\'Unclaimed Property'\'CT State'\2015\Jun"
Here is the latest error:
The problem is with the \ character, that has to be escaped.
This should work:
val input = "R:\\Unclaimed Property\\CT State\\2015\\Jun.ct_finderlist_2015.pdf"
val output = "R:\\Unclaimed Property\\CT State\\2015\\Jun"
A cleaner way to create string literals is to use triple quotes.
You can wrap your string directly in triple quotes without escaping special characters. And you can put multiple lines string in it.
It's much easier to code and read.
For example
val input =
"""
|R:\Unclaimed Property\CT State\2015\Jun.ct_finderlist_2015.pdf
"""
To add a variable to the string, do it like the following by adding "$variableName".
val input =
s"""
|R:\Unclaimed Property\$variablePath\CT State\2015\Jun.ct_finderlist_2015.pdf
"""

Implement Scala-style String Interpolation In Scala

I want to implement a Scala-style string interpolation in Scala. Here is an example,
val str = "hello ${var1} world ${var2}"
At runtime I want to replace "${var1}" and "${var2}" with some runtime strings. However, when trying to use Regex.replaceAllIn(target: CharSequence, replacer: (Match) ⇒ String), I ran into the following problem:
import scala.util.matching.Regex
val placeholder = new Regex("""(\$\{\w+\})""")
placeholder.replaceAllIn(str, m => s"A${m.matched}B")
java.lang.IllegalArgumentException: No group with name {var1}
at java.util.regex.Matcher.appendReplacement(Matcher.java:800)
at scala.util.matching.Regex$Replacement$class.replace(Regex.scala:722)
at scala.util.matching.Regex$MatchIterator$$anon$1.replace(Regex.scala:700)
at scala.util.matching.Regex$$anonfun$replaceAllIn$1.apply(Regex.scala:410)
at scala.util.matching.Regex$$anonfun$replaceAllIn$1.apply(Regex.scala:410)
at scala.collection.Iterator$class.foreach(Iterator.scala:743)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1174)
at scala.util.matching.Regex.replaceAllIn(Regex.scala:410)
... 32 elided
However, when I removed '$' from the regular expression, it worked:
val placeholder = new Regex("""(\{\w+\})""")
placeholder.replaceAllIn(str, m => s"A${m.matched}B")
res2: String = hello $A{var1}B world $A{var2}B
So my question is that whether this is a bug in Scala Regex. And if so, are there other elegant ways to achieve the same goal (other than brutal force replaceAllLiterally on all placeholders)?
$ is a treated specially in the replacement string. This is described in the documentation of replaceAllIn:
In the replacement String, a dollar sign ($) followed by a number will be interpreted as a reference to a group in the matched pattern, with numbers 1 through 9 corresponding to the first nine groups, and 0 standing for the whole match. Any other character is an error. The backslash (\) character will be interpreted as an escape character and can be used to escape the dollar sign. Use Regex.quoteReplacement to escape these characters.
(Actually, that doesn't mention named group references, so I guess it's only sort of documented.)
Anyway, the takeaway here is that you need to escape the $ characters in the replacement string if you don't want them to be treated as references.
new scala.util.matching.Regex("""(\$\{\w+\})""")
.replaceAllIn("hello ${var1} world ${var2}", m => s"A\\${m.matched}B")
// "hello A${var1}B world A${var2}B"
It's hard to tell what you're expecting the behavior to do. The issue is that s"${m.matched}" is turning into "${var1}" (and "${var2}"). The '$' is special character to say "place the group with name {var1} here instead".
For example:
scala> placeholder.replaceAllIn(str, m => "$1")
res0: String = hello ${var1} world ${var2}
It replaces the match with the first capturing group (which is m itself).
It's hard to tell exactly what you're doing, but you could escape any $ like so:
scala> placeholder.replaceAllIn(str, m => s"${m.matched.replace("$","\\$")}")
res1: String = hello ${var1} world ${var2}
If what you really want to do is evaluate var1/var2 for some variables in the local scope of the method; that's not possible. In fact, the s"Hello, $name" pattern is actually converted into new StringContext("Hello, ", "").s(name) at compile time.

Play framework, Display special characters

Hell, I am new to play framework and Scala. I don't know how to display special characters like #, -, "" as text.
Help!
If I got your question right, you are asking how to escape special characters in scala. It's pretty much same as other languages. using escape character \
val str = " \\\" " //output str: \"
or follow the below special syntax to store in string value with exactly what is inside the triple quotes.
val str = """ \" """ //output str: \"