2

I am new to Spark scala world and trying to learn it. I have a variable containing following value.

val result = "Scan value: 1802 seconds
Start time: Thu, Jan 31 2019, 15:09:09 GMT
End time: Thu, Jan 31 2019, 15:39:11 GMT"

I want to read scan value which is 1802 seconds and start time and End Time to different variables.

I am trying to use substring but I am not getting the results properly and the position may very the way the user enters.

For example: To read scan value, I am doing as follows. But some times these position might change based on how user enters in the system.

val scan_value = result.sbstring(13,4)

Could anyone please help me on how to read these values into separate variables in scala.

Thanks, Babu

4
  • 2
    Please show us some code that you tried Commented May 8, 2019 at 2:56
  • Hi Chaitanya, Thanks for your quick resposne and I have edited above on how I am trying to do it. Commented May 8, 2019 at 3:37
  • is the input going to be in this format always ? Commented May 8, 2019 at 5:25
  • Yes, we will receive it in the same format Commented May 8, 2019 at 5:39

2 Answers 2

2

Assuming the input will always be in the specified format, the following code will help you to extract out startTime and end time to their respective variables

val result = """ Scan value: 1802 seconds
Start time: Thu, Jan 31 2019, 15:09:09 GMT
  End time: Thu, Jan 31 2019, 15:39:11 GMT"""

val mayBeScanTime = result.split("Scan value:").find(_.contains("seconds")).map(_.split("seconds")(0).trim)


val startTime = Option(result.split("Start time:")(1).split("End time:")(0).trim)


val endTime = Option(result.split("End time:")(1).trim)

This will give you an output as

mayBeScanTime: Option[String] = Some(1802)


startTime: Option[String] = Some(Thu, Jan 31 2019, 15:09:09 GMT)


endTime: Option[String] = Some(Thu, Jan 31 2019, 15:39:11 GMT)

Please note that if the input string changes, the following code would not produce the correct result.

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

Comments

0

You can also try the following if the different values are always separated by newline.

val result = """Scan value: 1802 seconds
Start time: Thu, Jan 31 2019, 15:09:09 GMT
End time: Thu, Jan 31 2019, 15:39:11 GMT"""

val resultArray = result.split('\n')
val scanValue = resultArray.find(_.startsWith("Sc")).map(_.stripPrefix("Scan value: ").stripSuffix(" seconds"))
val startTime = resultArray.find(_.startsWith("St")).map(_.stripPrefix("Start time: "))
val endTime = resultArray.find(_.startsWith("E")).map(_.stripPrefix("End time: "))

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.