Pregunta

Say I have a formatting something like this: val format = "a=%d;b=%d;c=%d;d=%d". From this same String I want to get a regex that matches this.

 val format = "a=%d;b=%d;c=%d;d=%d"
 val regex = format2regex(format)

 def parse(input: String) = input match {
    case regex(aId, bId, cId, dId) => // input matches Format
    case _ => //
 }

 def format2regex(format: String): Regex = ???

What would be the body of the format2regex function? If impossible, is it possible to make an equivalent regex2format function?

¿Fue útil?

Solución

format string to regex

The function to translate a format to a regex could look like this:

import scala.util.matching._

val regex_mapping = Map(
  "%d" -> """((?:\\d+[.])?\\d+)"""
  //"%s" => ...
  //"%i" => ...
)

def format2regex(format: String) : Regex =
  ( regex_mapping.foldLeft(format)({ case (accum,(k,v)) => accum.replaceAll(k,v) }) ).r

Example

scala> val regex = format2regex(format)
regex: scala.util.matching.Regex = a=((?:\d+[.])?\d+);b=((?:\d+[.])?\d+);c=((?:\d+[.])?\d+);d=((?:\d+[.])?\d+)

Doing this has some real drawbacks:

  • the parse function wouldn't work like you wanted it to because the number of possible matching groups for in the Regular exppression can not be known in advance. Thus the number of arguments for the Extractor in the Pattern match is also unknown.

regex to format string Creating a format string of an arbitrary regex would be near to impossible or a least quite hard, as there a are many ways to formulate regular expressions that achieve the same goal. If you stick to to regular expression created by format2regex you could just inverse the mapping.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top