Dave's Brain

Browse - Programming Tips - Can I see some generalized functions for getting all the first and all matches?

Date: 2012dec21
Language: Scala

Q.  Can I see some generalized functions for getting all the first and all matches?

A.  I often want the first group in a match so this is how it works...

def getFirst(str_in: String, re: Regex): String = { re findFirstMatchIn str_in match { case None => "" case Some(hit) => hit.group(1).trim() } } def getAll(str_in: String, re: Regex): mutable.ArrayBuffer[String] = { var a = mutable.ArrayBuffer[String]() for (m <- re.findAllIn(str_in).matchData) { a += m.group(1).trim() } return a } def exampleUse() { val stuff = """name="Joe", name="Betty"""" val re = """(?s)name="(.*?)"""".r val first = getFirst(stuff, re) val a = getAll(stuff, re) }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.