Last active
March 20, 2021 17:57
-
-
Save StefRe/bb1669b511e8242fda88c58bc36ff447 to your computer and use it in GitHub Desktop.
Kotlin regex condition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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