https://kotlinlang.org logo
#getting-started
Title
# getting-started
i

Ink

05/05/2022, 4:21 PM
Hi guys! I have string like that:
[5-XR6Bwlq, 2-Hada32U1D, 7-aaGE7Ve84]
I want to get every single number before
-
and create list of Int with that values. How I can achive that?
k

Klitos Kyriacou

05/05/2022, 4:40 PM
Something like this, but you'll need to consider error handling:
Copy code
str.substring(1, str.length - 1).split(", ").map { it.substringBefore("-").toInt() }
n

nkiesel

05/05/2022, 5:35 PM
depends really on the details of your input, but something along the lines of
Copy code
Regex("""(\d+)-\w+""")
  .findAll(input)
  .map { it.groupValues[1].toInt() }
  .toList()
might work
i

Ink

05/05/2022, 5:42 PM
@nkiesel Thanks for help but it causes
NumberFormatException: Infinite or NaN
@Klitos Kyriacou Thank you, works as expected
n

nkiesel

05/05/2022, 5:44 PM
not for your input. Can you post the input for which my code fails?
<https://pl.kotl.in/R3atg3-Ax> is my test code. I added a version there which tolerates ill-formed input like
[1-ok, b-bad]
by using
Copy code
Regex("""(\d+)-[\w-]+""")
  .findAll(input1)
  .mapNotNull { it.groupValues[1].toIntOrNull() }
  .toList()
i

Ink

05/05/2022, 5:53 PM
Oh sorry, my bad. It crashes when I converted
null
.toString()