Skip to content

Instantly share code, notes, and snippets.

@StefRe
Last active March 20, 2021 17:57
Show Gist options
  • Save StefRe/bb1669b511e8242fda88c58bc36ff447 to your computer and use it in GitHub Desktop.
Save StefRe/bb1669b511e8242fda88c58bc36ff447 to your computer and use it in GitHub Desktop.
Kotlin regex condition
val scripts = listOf(
"""
if (1 != 0) {
document.writeln('valid');
}else{
document.writeln('invalid'); };
</script>""",
"""
if (0 != 0) {
document.writeln('valid');
}else{
document.writeln('invalid'); };
</script>""",
"""xxx""")
fun main() {
val regex = Regex("""if \((\d+) != 0\)""")
scripts.zip(listOf(true, false, false)){script, expected ->
// the straightforward way
val mr = regex.find(script)
var isValid = if (mr != null) mr.groupValues[1] != "0" else false
assert(isValid == expected)
// this also works but seems less clear
isValid = mr?.groupValues?.get(1) ?: "0" != "0"
assert(isValid == expected)
// without intermediate variable
isValid = regex.find(script)?.run{ groupValues[1] != "0" } ?: false
assert(isValid == expected)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment