I have information on Chess pieces in string format, for example: "Ka5Qb3a8b7"
, where "Ka5"
stands for King in a5, "Qb3"
for Queen in b3 and "a8"
for soldier in a8. So if '' then soldier.
How could I separate each piece to bring them later into respective objects? I guess I could loop through each index and match them to different cases and skip 1 or 2 following chars depending if soldier or not. However, I would prefer shorter and more readable code if that kind of approach exists.
I was first thinking to group into sizes of 3 but obviously not possible with soldiers taking only 2 letters. I'm using Scala.
Another option is to make the match a bit more specific listing all the available upper/lowercase chars and digits, where the uppercased chars are in an optional character class [KQNBR]?
using the questionmark.
"[KQNBR]?[a-h][1-8]".r.findAllIn("Ka5Qb3a8b7").toArray
res0: Array[String] = Array(Ka5, Qb3, a8, b7)
If the string is always in the same format, using split with lookarounds could also work.
"Ka5Qb3a8b7".split("(?<=\\d)(?=[A-Za-z])")
res0: Array[String] = Array(Ka5, Qb3, a8, b7)