Skip to content

Instantly share code, notes, and snippets.

@sofoklis
Created March 7, 2012 09:56
Show Gist options
  • Save sofoklis/1992310 to your computer and use it in GitHub Desktop.
Save sofoklis/1992310 to your computer and use it in GitHub Desktop.
scala regular expressions example
case class Line(id : Long, yesNo : Boolean, name : String, optional : Option[String], amount : Double)
object SimpleImport {
// Create the field regex so you can compose them
//and be able to simply extract the information
val sourceFolder : String = "/home/sofoklis/Desktop"
val digit = """~(\d*)~"""
val double = """([-+]?[\d]*\.?[\d]+)*"""
val text = """~([^~]*)~"""
val separator = """\^"""
// Create a simple function that will create an option from a string value
def optionString(text : String) = text match {
case null ⇒ None
case t ⇒ t.trim match {
case "" ⇒ None
case value ⇒ Some(value)
}
}
// Convert whatever is a boolean in your files to a scala Option[boolean]
def booleanFromString(value : String) : Option[Boolean] = value match {
case null ⇒ None
case ex ⇒ ex.trim match {
case "" ⇒ None
case "Y" ⇒ Some(true)
case "y" ⇒ Some(true)
case "N" ⇒ Some(false)
case "n" ⇒ Some(false)
case _ ⇒ Some(false)
}
}
def main(args : Array[String]) {
ImportSample.loadData
println("Finished")
}
}
object ImportSample {
import SimpleImport._
val fileName = "sample"
// This is where the magic happens, simply create a list of the fields you expect and
// create a regular expression for your full line
val RegEx = List(digit, text, text, text, double).mkString(separator).r
def loadData {
// Get the file and read the lines
val filePath = sourceFolder + "/" + fileName
import scala.io.Source._
val lines = fromFile(filePath).getLines
//Loop the lines and match
lines.foreach(line ⇒ line match {
case RegEx(id, yesNo, name, optional, amount) ⇒ println(Line(id.toLong,
booleanFromString(yesNo).get,
name, optionString(optional), amount.toDouble))
case _ ⇒ println("Something Wrong!")
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment