0

given the following strings...

val s0 = "objects"
val s1 = "/objects"
val s2 = "/objects(0)"
val s3 = "/objects(1)"

I need to extract the substring objects, regardless of any possible prefix and suffix. If the string always started with a slash and ended with (N), then easiest solution would be

scala> s3.substring(1).substring(0, s3.indexOf("(") - 1)
res1: String = objects

How do I always extract the string objects with a regex (I suppose this is the way to go)?

3
  • 1
    What are you actually trying to do? If you know the exact string that you want to extract, why do you need to extract it at all? Commented Jun 14, 2015 at 15:03
  • 1
    Do you just want to check whether a string contains the substring objects? Commented Jun 14, 2015 at 15:03
  • Was just an example to explain that I need to extract a string between / and (N) (/ and (N) might or might not be present). Commented Jun 14, 2015 at 15:10

3 Answers 3

2

You could use the below regex and get the string you want from group index 1.

^\/?(.*?)(?=(?:\(\d*\))?$)

DEMO

Sign up to request clarification or add additional context in comments.

Comments

2

Here is another way to do this:

val pattern = """.*/(objects)\(\d+\).*""".r

val data = Seq("objects", "/objects", "/objects(0)", "/objects(1)")

val results = data.map{
    case pattern(obj) => obj
    case _ => "-"
}

Scala REPL:

results: Seq[String] = List(-, -, objects, objects)

Comments

1

Knowing the delimiting characters allows for this use of dropWhile and takeWhile; for

val in = Seq("objects", "/objects", "/objects(0)", "/objects(1)")

then

in.map(i => i.dropWhile(_ == '/').takeWhile(_ != '('))
List(objects, objects, objects, objects)

A regular expression with grouping as already suggested proves more robust, scalable and general otherwise.

Comments

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.