DEV Community

moose
moose

Posted on

Kotlin Pure Regex Routing Logic

This article is just going to be a step my step of my turn sketch of utilizing pure regex patterns to develop complex and robust routing logic that is extremely lightweight, compact and configurable. In this example we will take a look at whats going on in the code. Let's do it.

Regex.kt

These are regex checkers that do protocol match checks

//     ft or ftps
var ftpReg = Regex("(ftp|ftps://)")

//    https or https
var httpReg = Regex("(?:(http|https)"

//. http://www.example.com
//takes to root directorty of any site
var httpReg = Regex("(?:(http|https)://\\w{1,})(\\.)")

//Handles site queries
//this is also dynamically expandable and contractable
var httpReqReg = Regex("(?:(http|https)://\\w+)(\\.)(\\w+\\2\\w+)/(?:\\w+[/]?){0,}(?:\\?)?(\\w+=\\\"[a-z]+\\\"&?)+")
Enter fullscreen mode Exit fullscreen mode

These are the email links

/*
These are the URLs being matched and routed through proxy
Sorts protocol, site+(n(directories))+(n(query/params))
*/
var ftpReg = Regex("(ftp|ftps://)")
var https  = "https://wwww.google.com"
var http = "http://wwww.nigel.com"
var ftp = "ftp://modog"
var hReqURL = "https://www.google.com/asdasd/asdasd/asdas?someVar=\"y\"&someVar=\"y\"&someVar=\"y\""
Enter fullscreen mode Exit fullscreen mode

Here is the execution


    var urlArray = arrayOf(http, https, ftp, hReqURL)
    for(url in urlArray) {
        when {
            httpReg.containsMatchIn(url) -> {
                println(url)
            }
            ftpReg.containsMatchIn(url) -> {
                println(url)
            }
            httpReqReg.containsMatchIn(url) -> {
                println(url)
            }
        }
    }

Enter fullscreen mode Exit fullscreen mode

Here is the whole file now together:


fun main(){
    var httpReg = Regex("(?:(http|https)://\\w{1,})(\\.)") //just the sit
    var httpReqReg = Regex("(?:(http|https)://\\w+)(\\.)(\\w+\\2\\w+)/(?:\\w+[/]?){0,}(?:\\?)?(\\w+=\\\"[a-z]+\\\"&?)+")
    var ftpReg = Regex("(ftp|ftps://)")
    var https  = "https://wwww.google.com"
    var http = "http://wwww.nigel.com"
    var ftp = "ftp://modog"
    var hReqURL = "https://www.google.com/asdasd/asdasd/asdas?someVar=\"y\"&someVar=\"y\"&someVar=\"y\""
    var urlArray = arrayOf(http, https, ftp, hReqURL)
    for(url in urlArray) {
        when {
            httpReg.containsMatchIn(url) -> {
                println(url)
            }
            ftpReg.containsMatchIn(url) -> {
                println(url)
            }
            httpReqReg.containsMatchIn(url) -> {
                println(url)
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)