maloney maloney - 29 days ago 10
Scala Question

Split regex in Scala keeping delimiter

I'm trying to split a string using Regex with some rules:


  • The string should be split into 2 with the the first part containing at least 2 characters

  • The second part is made up of all characters starting with the first number (after the second character)



e.g. AB1234 = AB and 1234 , C56789 = C5 and 6789 , ZYX3939Y = ZYX and 3939Y

I have this Regex which is nearly working, but it loses the character it is splitting on:

val t = request.number.split("(?<=.{2})[0-9]{1}", 2)


println(t(0), t(1))


Gives:

(AB,234)
(C5,789)
(EZY,9393Y)


What is the correct regex and is there an easier way of doing this?

Answer

You would be better off using span and splitAt methods on String.

val (twoFirst, rest) = request.number.splitAt(2)
val (noNumber, tail) = rest.span(!_.isDigit)
(twoFirst + noNumber, tail)

The first val splits the input after the second character. The second val splits the input as soon as it finds a digit.