How to print any alphabet after $ sign in Kotlin? [duplicate] - kotlin

What is the cleanest method for adding a $ character in a string literal?
The best solution I've come up with so far is """${"$"}...""", which looks ugly to me.

To escape the dollar sign inside a string literal, use the backslash character:
"\$"
To escape it in a raw string literal ("""..."""), the workaround you provided is indeed the easiest solution at the moment. There's an issue in the bug tracker, which you can star and/or vote for: KT-2425.

In current Kotlin 1.0 (and betas) you can just escape with backslash "\$"
This passing unit test proves the cases:
#Test public fun testDollar() {
val dollar = '$'
val x1 = "\$100.00"
val x2 = "${"$"}100.00"
val x3 = """${"$"}100.00"""
val x4 = "${dollar}100.00"
val x5 = """${dollar}100.00"""
assertEquals(x5, x1)
assertEquals(x5, x2)
assertEquals(x5, x3)
assertEquals(x5, x4)
// you cannot backslash escape in """ strings, therefore:
val odd = """\$100.00""" // creates "\$100.00" instead of "$100.00"
// assertEquals(x5, odd) would fail
}
All versions make a string "$100.00" except for the one odd case at the end.

It doesn't look like you pasted your code correctly as you only have 3 double quotes.
Anyhow, the best way to do this is to just escape the dollar sign as follows:
"\$"

To get literal dollar signs shows in multi-line strings, you can do the below
I'm sorry for my sins:
val nonInterpedValue = "\${someTemplate}"
val multiLineWithNoninterp = """
Hello
$nonInterpedValue
World
""".trimIndent()
As mentioned elsewhere, this is the workaround because right now you can't use dollar signs inside multi-line strings. https://youtrack.jetbrains.com/issue/KT-2425
( I needed this to get Groovy's Template Engine working: https://www.baeldung.com/groovy-template-engines)

For Kotlin developers.
What I wanted to do was this:
val $name : String
If that's your case too, use this:
val `$name` : String

Related

Kotlin query: Replace all the words in the string starting and ending with $ e.g. $lorem$ to <i>lorem<\i>

I am stuck on the following code challenge in Kotlin:
Replace all the words in the string starting and ending with $ e.g. $lorem$ to <i>lorem</i>
var incomingString = "abc 123 $Lorem$, $ipsum$, $xyz$ 547"
// My non working code:
fun main(args: Array<String>) {
val incomingString = "abc 123 \$Lorem$, \$ipsum$, \$xyz$ 547";
var finalString = "";
println(filteredValue)
if (incomingString.contains("$")){
val intermediateString = incomingString.replace("\$", "<i>")
finalString = "$intermediateString</i>"
}
println(finalString)
}
Output is:
abc 123 <i>Lorem<i>, <i>ipsum<i>, <i>xyz<i> 547</i>
Desired output:
abc 123 <i>Lorem</i>, <i>ipsum</i>, <i>xyz</i> 547</i>
I am not going to do your home work for you, but the reason why you have a challenge including $ is that symbol has two special purposes
Read up about String Interpolation in Kotlin: https://kotlinlang.org/docs/idioms.html#string-interpolation ... you will need to take care to prevent the $ being used for interpolation ... and seems you already got that part
$ is also a special character in Regular Expressions. Regular Expressions are an esoteric area of programming - meaning very complicated to get your head around, but very very powerful. Worth the effort. Using Regular Expression (Regex) approach for this program is what will get you lots of marks if you can also be sure to escape the $. Here is the Kotlin Regex replace function docs:
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-regex/replace.html
Every time you come across a $ in your input string, you need to alternate between replacing it with <i> and replacing it with </i>. Therefore, you need to have a variable that tells you what state you're in, and every time you make a replacement, you flip that variable. You may find Kotlin's String.replaceFirst method useful.

unescaping UTF-8 characters from file (InputStream)

I am trying to unescape UTF_8 characters like "\u00f6" to their UTF-8 representation.
E.g. file contains "Aalk\u00f6rben" should become "Aalkörben".
val tmp = text.toByteArray(Charsets.UTF_8)
val escaped = tmp.decodeToString()
// or val escaped = tmp.toString(Charsets.UTF_8)
When I set the string manually to "Aalk\u00f6rben", this works fine. However, when reading the string from the file it is interpreted like "Aalk\\u00f6rben" with the slash escaped (two slashes) and the escaping fails.
Is there any way to convince Kotlin to convert the special characters? I would rather not use external libraries like from Apache.
I do not know how you read the file, but what happens most probably is that ...\u00f6... is read as six single characters and the backslash is probably being escaped. You could check in the debugger.
So my assumption is that in memory you have "Aalk\\u00f6rben". Try this replace:
val result = text
.replace("\\u00f6", "\u00f6")
.toByteArray(Charsets.UTF_8)
.decodeToString()
Edit: this should replace all escaped 4 byte characters:
val text = Pattern
.compile("\\\\u([0-9A-Fa-f]{4})")
.matcher(file.readText())
.replaceAll { matchResult -> matchResult.group(1).toInt(16).toChar().toString() }

Escape hex like \u... in kotlin strings

I have a string "\ufffd\ufffd hello\n"
i have a code like this
fun main() {
val bs = "\ufffd\ufffd hello\n"
println(bs) // �� hello
}
and i want to see "\ufffd\ufffd hello", how can i escape \u for every hex values
UPD:
val s = """\uffcd"""
val req = """(?<!\\\\)(\\\\\\\\)*(\\u)([A-Fa-f\\d]{4})""".toRegex()
return s.replace(unicodeRegex, """$1\\\\u$3""")
(I'm interpreting the question as asking how to clearly display a string that contains non-printable characters.  The Kotlin compiler converts sequences of a \u followed by 4 hex digits in string literals into single characters, so the question is effectively asking how to convert them back again.)
Unfortunately, there's no built-in way of doing this.  It's fairly easy to write one, but it's a bit subjective, as there's no single definition of what's ‘printable‘…
Here's an extension function that probably does roughly what you want:
fun String.printable() = map {
when (Character.getType(it).toByte()) {
Character.CONTROL, Character.FORMAT, Character.PRIVATE_USE,
Character.SURROGATE, Character.UNASSIGNED, Character.OTHER_SYMBOL
-> "\\u%04x".format(it.toInt())
else -> it.toString()
}
}.joinToString("")
println("\ufffd\ufffd hello\n".printable()) // prints ‘\ufffd\ufffd hello\u000a’
The sample string in the question is a bad example, because \uFFFD is the replacement character — a black diamond with a question mark, usually shown in place of any non-displayable characters.  So the replacement character itself is displayable!
The code above treats it as non-displayable by excluding the Character.OTHER_SYMBOL type — but that will also exclude many other symbols.  So you'll probably want to remove it, leaving just the other 5 types.  (I got those from this answer.)
Because the trailing newline is non-displayable, that gets converted to a hex code too.  You could extend the code to handle the escape codes \t, \b, \n, \r and maybe \\ too if needed.  (You could also make it more efficient… this was done for brevity!)
Simply escape the \ in your strings by adding another backslash in front of it:
val bs = "\\ufffd\\ufffd hello\n"
You can also use raw strings with """ so you don't have to escape the backslashes (which is useful for regex):
val bs = """\ufffd\ufffd hello\n"""
Note that in that case the \n would also NOT be counted as an LF character, and will be literally printed as the 2 characters "\n".
You can add literal line breaks in your raw string if you want an actual line feed, though:
val bs = """\ufffd\ufffd hello
"""

Escape String interpolation in a string literal

In a normal String I can escape the ${variable} with a backslash:
"You can use \${variable} syntax in Kotlin."
Is it possible to do the same in a String literal? The backslash is no longer an escape character:
// Undesired: Produces "This \something will be substituted.
"""This \${variable} will be substituted."""
So far, the only solutions I see are String concatenation, which is terribly ugly, and nesting the interpolation, which starts to get a bit ridiculous:
// Desired: Produces "This ${variable} will not be substituted."
"""This ${"\${variable}"} will not be substituted."""
From kotlinlang.org:
If you need to represent a literal $ character in a raw string (which doesn't
support backslash escaping), you can use the following syntax:
val price = """
${'$'}9.99
"""
So, in your case:
"""This ${'$'}{variable} will not be substituted."""
As per String templates docs you can represent the $ directly in a raw string:
Templates are supported both inside raw strings and inside escaped strings. If you need to represent a literal $ character in a raw string (which doesn't support backslash escaping), you can use the following syntax:
val text = """This ${'$'}{variable} will be substituted."""
println(text) // This ${variable} will be substituted.

Password regex not working in Kotlin

I am trying to run the below code to validate a password string against my regex. But it's always returning false. What am I doing wrong ?
fun main(args: Array<String>) {
val PASSWORD_REGEX = """^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%!\-_?&])(?=\\S+$).{8,}""".toRegex()
val password:String = "Align#123"
println(PASSWORD_REGEX.matches(password))
}
You are using raw strings but are escaping the last \S which is causing a literal match of \S. If I remove the extra backslash, your test case works for me. And as others have stated, you might be able to remove that stanza entirely.
So this...
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%!\-_?&])(?=\\S+$).{8,}
^
|
Remove -+
Becomes this
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%!\-_?&])(?=\S+$).{8,}
I used Regex101 to help me, which seems to be a nice way to turn regex into English.