Skip to content

Instantly share code, notes, and snippets.

@goreilly
Created February 1, 2018 23:22
Show Gist options
  • Save goreilly/06d83ea3bca7e806a7190f5d0d6600dd to your computer and use it in GitHub Desktop.
Save goreilly/06d83ea3bca7e806a7190f5d0d6600dd to your computer and use it in GitHub Desktop.
Parse CSS colors in Kotlin
class Color(val red: Int, val green: Int, val blue: Int, val alpha: Float) {
companion object {
private val pattern = Pattern.compile("^rgba?\\((\\d+), (\\d+), (\\d+)(?:, ([\\d.]+))?\\)$")
fun fromString(string: String): Color? {
val matcher = pattern.matcher(string)
if (!matcher.matches()) return null
val red = matcher.group(1).toInt()
val green = matcher.group(2).toInt()
val blue = matcher.group(3).toInt()
val alpha = matcher.group(4)?.toFloat() ?: 1.0f
return Color(red, green, blue, alpha)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment