Skip to content

Regex Tester — Kotlin source

Test regular expressions against any text with all flags (g/i/m/s/u/y). See every match, its index and capture groups, plus the constructed pattern. 100% in-browser.

This is the Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.

// regex-tester — Kotlin port. Match a pattern against text, report every
// match with capture groups and index (kotlin.text.Regex, JDK engine).
import java.util.regex.PatternSyntaxException

data class RegexMatch(val match: String, val index: Int, val groups: List<String>)

object RegexTester {
    // JS flag letters -> RegexOption. g selects findAll vs first match;
    // u is the default for String patterns; y has no equivalent.
    private fun compileOptions(flags: String): Set<RegexOption> = buildSet {
        if ('i' in flags) add(RegexOption.IGNORE_CASE)
        if ('m' in flags) add(RegexOption.MULTILINE)
        if ('s' in flags) add(RegexOption.DOT_MATCHES_ALL)
    }

    fun runRegex(pattern: String, flags: String, text: String): List<RegexMatch> =
        try {
            val re = Regex(pattern, compileOptions(flags))
            val found = if ('g' in flags) re.findAll(text)
                        else generateSequence(re.find(text)) { null }
            found.take(2000).map { m ->
                RegexMatch(m.value, m.range.first, m.groupValues.drop(1))
            }.toList()
        } catch (e: PatternSyntaxException) {
            System.err.println("error: ${e.message}")
            emptyList()
        }

    // Render a result the way the tool's UI does:
    // `N. "match" @ index -> [g1, g2]`, or `(none)` when empty.
    fun formatMatches(ms: List<RegexMatch>): String =
        if (ms.isEmpty()) "(none)"
        else ms.mapIndexed { i, m ->
            "${i + 1}. \"${m.match}\" @ ${m.index}" +
                (if (m.groups.isNotEmpty()) " -> [${m.groups.joinToString(", ")}]" else "")
        }.joinToString("\n")
}

fun main() {
    val ms = RegexTester.runRegex("""(\w+)@(\w+)\.(\w+)""", "g", "mail@x.com nope bob@test.org")
    println(RegexTester.formatMatches(ms))
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →