Kotlin extension functions for Strings

A collection of Kotlin extension methods that simplify many common tasks related to strings.

fun String.nullIfEmpty() = if (this.isNotEmpty()) this else null

fun String.orIfBlank(s: String?): String? = if (this.isEmpty() || this.isBlank()) s else this

fun String.containedIn(dest: Array<String>, isExact: Boolean) =
        when (isExact) {
            true -> dest.contains(this)
            false -> {
                dest.forEach {
                    if (it.contains(this)) {
                        return true
                    }
                }
                false
            }
        }

Crypto

fun String.hashMac(secretKey: String): String {
    val key = SecretKeySpec(secretKey.toByteArray(), "HmacSHA256")
    val mac = Mac.getInstance(key.algorithm)
    mac.init(key)
    val hmac = mac.doFinal(this.toByteArray())
    val sb = StringBuilder(hmac.size * 2)
    val formatter = Formatter(sb)
    for (b in hmac) {
        formatter.format("%02x", b)
    }
    return sb.toString()
}

Validation

fun String.isValidEmail(): Boolean =
    this.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches()

fun String.isAcceptablePassword(): Boolean =
    this.isNotEmpty() && this.length > 3

fun String.isValidPhoneNumber(): Boolean =
    this.isNotEmpty() && Patterns.PHONE.matcher(this).matches()

fun String.isValidUrl(): Boolean = 
    this.isNotEmpty() && Patterns.WEB_URL.matcher(this).matches()

fun String.isValidIP(): Boolean =
    this.isNotEmpty() && Patterns.IP_ADDRESS.matcher(this).matches()

fun String.isValidWebsite() : Boolean =
        this.isValidUrl() || this.isValidIP()

URLS

fun String.urlencode() = URLEncoder.encode(this, "utf-8")

/**
 * Returns a map of query parameters in a string
 */
@Throws(UnsupportedEncodingException::class)
fun String.parseQueryStrings(): LinkedHashMap<String, String?> {
    val map = LinkedHashMap<String, String?>()
    val pairs = this.split("&")
    for (pair in pairs) {
        val idx = pair.indexOf("=")
        val key = if (idx > 0) URLDecoder.decode(pair.substring(0, idx), "UTF-8") else pair
        val value = if (idx > 0 && pair.length > idx + 1) URLDecoder.decode(pair.substring(idx + 1), "UTF-8") else null
        map.put(key, value)
    }
    return map
}

Imports for the above methods

import android.util.Patterns
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec