Categories
Scala

Extract text between two strings with Scala regex

Scala as a very light syntax compared to Java. To extract the text between two strings tag1 and tag2 from the string content, we can use the Scala regex syntax. We only need 2 lines of code:

 val pattern = "(?<=tag1).*(?=tag2)".r
 val extracted = pattern.findFirstIn(content).get

You can print extracted in a main:

package com

object Main {
  def main(args: Array[String]): Unit = {
    val content = "blablatag1extract me !tag2 blalalalala"
    val pattern = "(?<=tag1).*(?=tag2)".r
    val extracted = pattern.findFirstIn(content).get

    println(extracted)
  }
}

When you execute the code above, you will get the following result in the console:

extract me !

Leave a Reply

Your email address will not be published. Required fields are marked *