Regex matching with custom patterns
Custom patterns that wrap regular expressions so a match reads like a literal.
module contactInformation
import nanyx/text.regex
-- Custom patterns wrap the regular-expression matching, so that the match
-- reads as if the language had email-address and phone-number literals.
-- Single-quoted strings are raw, which suits regular expressions.
def emailPattern = Regex('^(\w+)@(\w+(\.\w+)+)$')
def phonePattern = Regex('^\d{3}-\d{3}-\d{4}$')
pattern string -> #Email(localPart: string, domain: string) | _ = { s ->
match emailPattern \captures(s)
| #some([localPart, domain, ...]) -> #Email(localPart = localPart, domain = domain)
| _ -> _
}
pattern string -> #Phone(string) | _ = { s ->
if phonePattern \matches(s) then #Phone(s) else _
}
def saveContactInformation: [Console] string -> () = {
| #Email(localPart, ...) -> println("Hi {localPart}, we have saved your email address.")
| #Phone(number) -> println("Hi, we have saved your phone number {number}.")
| _ -> println("Invalid contact information: neither an email address nor a phone number.")
}
@entry
def main = {
saveContactInformation("123-456-7890")
saveContactInformation("JohnSmith@sample.domain.com")
saveContactInformation("2 Franklin St, Mars, Milky Way")
}
This program lives in the repository as examples/regex-matching.nyx.