This is my current code to match a command: ```pr...
# announcements
t
This is my current code to match a command:
Copy code
private fun extractCommand(command: String): Boolean {
    val asArr = command.split("\\s")
    if (asArr[0].equals(".attack", ignoreCase = true) && asArr.size == 3)
        return true
}
Is there a way to do this with regex? I think that's the best way
t
split
can be used with
Regex
(3rd declaration)
n
Copy code
private fun extractCommand(command: String) = Regex("""(?i)\.attack\s+\S+\s+\S+""").matches(command)
caveat: I might misunderstand your goal (why is it call "extract" is it does not return an extracted part?)
t
@nkiesel yes... mistake on my part
e
1. if used repeatedly, compile the regex once, not multiple times. also more idiomatic to use the extension rather than the constructor
2. at some point I assume you want to use other values too... in which case you can use capturing groups
Copy code
val pattern = """(\S+)\s+(\S+)\s+(\S+)""".toRegex()
fun extractAttack(command: String): Boolean {
    val (part1, part2, part3) = pattern.matchEntire(command)?.destructured
        ?: return false
    return part1 == ".attack"
}
if you did that, you'd be able to re-use the regex for other lines of the same form, as well as have easy access to the other captured groups
t
@ephemient interesting code...