Scala 模板:将字符串映射到模板
Scala Templates: Map a String to a Template
我使用 Scalate 进行模板化。通常是这样的:
模板:
Hello {{name}}
参数:
`地图(“姓名”->“彼得”)
结果:
Hello Peter
有没有办法得到参数图作为结果?
模板:
Hello {{name}}
要求:
Hello Peter
结果:
Map("name" -> "Peter")
也许您正在寻找具有命名组的正则表达式?
//Regex with named groups
val pattern = """^Hello (?<firstname>\w+) (?<lastname>\w+)$""".r
val groups = List(
"firstname",
"lastname"
)
def matchAll(str: String): Option[Map[String, String]] = pattern
.findFirstMatchIn(str)
.map { matched =>
groups.map(name => name -> matched.group(name)).toMap
}
matchAll("Hello Joe Doe") //Some(Map(firstname -> Joe, lastname -> Doe))
我使用 Scalate 进行模板化。通常是这样的:
模板:
Hello {{name}}
参数:
`地图(“姓名”->“彼得”)
结果:
Hello Peter
有没有办法得到参数图作为结果?
模板:
Hello {{name}}
要求:
Hello Peter
结果:
Map("name" -> "Peter")
也许您正在寻找具有命名组的正则表达式?
//Regex with named groups
val pattern = """^Hello (?<firstname>\w+) (?<lastname>\w+)$""".r
val groups = List(
"firstname",
"lastname"
)
def matchAll(str: String): Option[Map[String, String]] = pattern
.findFirstMatchIn(str)
.map { matched =>
groups.map(name => name -> matched.group(name)).toMap
}
matchAll("Hello Joe Doe") //Some(Map(firstname -> Joe, lastname -> Doe))