KLibRegexDsl
A tiny Regex DSL library for Kotlin Multiplatform.
Why
Regular expressions are a powerful tool, but a bit of a nightmare to read and maintain. In fact, they aren't ideal to write either: the syntax is not always intuitive or simple to remember, and it's quite easy to make mistakes - which will typically be detected at run-time only.
Using a DSL instead fixes these issues (albeit at the cost of verbosity - but as Kotlin developers, we like verbose, don't we?)
As an illustration, compare these two ways to express "Time Format HH:MM 12-hour, optional leading 0":
vs
Which one is easier to read?
Fooled you - the first one isn't even valid (duplicated bracket)! You may have missed it, but I don't blame you: it is easy to miss.
As a bonus, an explicit API can abstract platform-specific differences (did you know . doesn't have the exact same meaning on JVM, JS and native? See 'Portability' section below).
If that convinced you, continue reading.
Usage
1/ Add the dependencies to your project
(The artifact is hosted on Maven Central)
2/ Use it
The API is pretty self-explanatory so here's an example:
You can also have a look at the sample.
Portability
KLibRegexDsl targets the JVM, JavaScript, and Kotlin/Native on Apple platforms (macOS arm64, iOS arm64, and iOS simulator arm64).
The API in org.jraf.klibregexdsl is safe to use from commonMain: its predefined character classes and operators have the same matching behavior on every supported target. This includes ASCII classes such as AsciiAlphanumeric, Unicode general categories such as UnicodeLetter, and portable WhitespaceCharacter, AnyCharacter, and word-boundary matchers.
toString() returns a diagnostic representation that can differ by target - use toRegex() to obtain a regex that adheres to the portability contract.
Engine-specific features are kept out of common code. JVM-only classes and anchors live in org.jraf.klibregexdsl.jvm:
JVM code can also use QuantifierType.POSSESSIVE; common, JavaScript, and Native code only expose GREEDY and RELUCTANT.
Raw deliberately bypasses these guarantees. Use it only when the caller owns the target regex syntax.