Skip to content
Philipp Ploder edited this page Jul 16, 2017 · 2 revisions

Regular Map is a simple library that makes mapping matches from regular expressions to objects extremely simple.

See the annotations page for information about the annotations.

Mapping to an object

Let's assume we want to map a person's first and last name to an object.

First we create a data class to store the persons data. The @NamedGroup annotations defines which value the property should have, in this case we want a named group.

data class Person(@NamedGroup("firstname") val firstname: String, @NamedGroup("lastname") val lastname: String)

The second step is to call the extension function on the pattern with the input as the only parameter.

val pattern = Pattern.compile("(?<firstname>[a-z]+)[ ](?<lastname>[a-z]+)", Pattern.CASE_INSENSITIVE)
val person = pattern.mapObject<Person>("Philipp Ploder")

Now the person variable will contain an instance of the Person class with the firstname property set to Philipp and the lastname property set to Ploder. Note that the values were not injected directly. The values were simply passed to the constructor. In fact, the target class does not need to be a data class. Each constructor parameter has to be annotated with an annotation defining which value to pass and the type has to be compatible with the type defined for the annotation in the relevant wiki page. If the class has multiple constructors the one that should be used has to be annotated with the @RegularMapTarget annotation.

Mapping to a function call

Mapping to function calls is also supported. Each parameters has to be annotated with a relevant annotation and have a type that is compatible with the type specified by the annotation. Below you can see the above pattern being used to print a formatted text to the console.

fun printPerson(@NamedGroup("firstname") firstname: String, @NamedGroup("lastname") lastname: String) =
    println("Firstname: $firstname, Lastname: $lastname")

val pattern = Pattern.compile("(?<firstname>[a-z]+)[ ](?<lastname>[a-z]+)", Pattern.CASE_INSENSITIVE)
pattern.mapCall(::printPerson, "Philipp Ploder")

If the printPerson function had a return value then mapCall would return the value returned by the function.

Clone this wiki locally