-1

I would like to extract two numbers for a strings by regex "[0-9]+"

var str = "ABcDEFG12345DiFKGLSG938SDsFSd"

What I want to extract is "12345" and "938".

But I am not sure how to do so in Kotlin.

Peter Haddad
  • 65,099
  • 21
  • 108
  • 107
Kenneth Yau
  • 59
  • 2
  • 6

1 Answers1

0

This should work:

import java.util.regex.Matcher
import java.util.regex.Pattern

fun main(args:Array<String>) {
val p = Pattern.compile("\\d+")
val m = p.matcher("ABcDEFG12345DiFKGLSG938SDsFSd")
while (m.find())
{
  println(m.group())
}
}

Pattern.compile("\\d+"), it will extract the digits from the expression.

Peter Haddad
  • 65,099
  • 21
  • 108
  • 107
  • 3
    You could make this approach more Kotlin idiomatic using `val p = Regex("\\d+")`, `val s = "ABcDEFG12345DiFKGLSG938SDsFSd"` and then `pattern.findAll(s).forEach { println(it.value) }`. – Henning Dodenhof Oct 13 '17 at 09:41