2

In Scala I have a string of the form

val str = "[ab][bc][cd][dx][42]"

What is the most efficient way in Scala, regular expression utilizing or otherwise, to split that string into a Seq[String] that would be of the form:

("ab","bc","cd","dx","42")

Thank you.

5 Answers 5

6

You can try this:

val str = "[ab][bc][cd][dx][42]"
val res = str.drop(1).sliding(2, 4).toList
println(res) // List(ab, bc, cd, dx, 42)

val str2 = "[ab]"
val res2 = str2.drop(1).sliding(2, 4).toList
println(res2) // List(ab)

val str3 = ""
val res3 = str3.drop(1).sliding(2, 4).toList
println(res3) // List()
Sign up to request clarification or add additional context in comments.

Comments

4

you can try:

str.split("(\\]\\[)|(\\[)|(\\])").filterNot(_.isEmpty)

Mainly using groups (][, ], [) for delimiter and trimming the array.

Comments

2

You can use this regex:

(?<=\[)([^]]+)(?=\])

RegEx Demo

Code:

scala> val re = "(?<=\\[)([^]]+)(?=\\])".r
re: scala.util.matching.Regex = (?<=\[)([^]]+)(?=\])

scala> for(m <- re.findAllIn("[ab][bc][cd][dx][42]")) println(m)
ab
bc
cd
dx
42

Comments

1

Assuming ][ is the delimiter between any two consecutive items, consider

str.drop(1).dropRight(1).split("\\]\\[")

delivers

Array("ab", "bc", "cd", "dx", "42")

Update

A tiny bit more general an approach, where we define String delimiters,

implicit class Spl(val str: String) extends AnyVal {
  def regSplit(leftDel: String, rightDel: String) = 
    str.stripPrefix(leftDel).stripSuffix(rightDel).split(rightDel+leftDel)
}

Thus

str.regSplit("\\[","\\]")
res: Array[String] = Array([ab, bc, cd, dx, 42])

Comments

0
\[([^\]]+)\]

The easiest and most logical way is to match and not split.Just match and grab the captures or group 1.See demo.

https://regex101.com/r/gQ3kS4/42

1 Comment

How would I implement the match in scala?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.