https://kotlinlang.org logo
#random
Title
# random
c

Colton Idle

07/07/2022, 2:59 PM
Anyone good with regex? What is this actually splitting my string on?
Copy code
myCowboy.split("\\$")
s

Sam

07/07/2022, 3:01 PM
If it was a regex pattern, it would match a dollar sign
"\\" is escaping the
\
in the Kotlin string
so the actual regex pattern is
\$
e

ephemient

07/07/2022, 3:02 PM
in Kotlin, String.split(String) doesn't split on a pattern, it splits on a literal match
s

Sam

07/07/2022, 3:02 PM
Yeah, I was just about to remember that
e

ephemient

07/07/2022, 3:02 PM
this is different (but saner) than Java's String.split
c

Colton Idle

07/07/2022, 3:03 PM
sorry. it is actually
Copy code
.split(regex = "\\$".toRegex())
i tried to simplify and bit myself
okay. so its splitting on a dollar sign. interesting. thank you
e

ephemient

07/07/2022, 3:04 PM
you could also write
Copy code
"""\$""".toRegex()
backslashes don't need to be escaped in multiline quotes
3
s

sreich

07/07/2022, 3:54 PM
i recommend using online regex editors btw. they're a tremendous help and visualize what's happening in the matcher system
c

Colton Idle

07/07/2022, 4:05 PM
Yeah. I tried but what getting different results depending if I had an extra \ and so I was just confused if the online tool was getting escaped or not
k

Klitos Kyriacou

07/07/2022, 4:10 PM
However, In this particular case, you can just do
myCowboy.split('$')
❤️ 1
n

nkiesel

07/07/2022, 11:42 PM
or
myCowboy.split("$")
. Normally, you would have to quote the
$
in strings if you want a literal
$
because of Kotlin's templating. However, a
$
at the end of a String literal does not require quoting.
1
e

ephemient

07/07/2022, 11:44 PM
$
before anything that doesn't look like interpolation will work without escaping
n

nkiesel

07/07/2022, 11:45 PM
yup
e

ephemient

07/07/2022, 11:45 PM
"$0"
,
"$$"
,
"$[]"
, etc.
should you use that, maybe not. but it works
4 Views