Is there a better way to compose/reuse Regex patte...
# general-advice
z
Is there a better way to compose/reuse Regex patterns than interpolating
.pattern
?
Copy code
val alphaNumericHyphen = Regex("[A-Za-z0-9\\-]");
val atLeastOneAlphaNumericHyphen = Regex("${alphaNumericHyphen.pattern}+")
val xAlphaNumericHyphen = Regex("[Xx]-${alphaNumericHyphen.pattern}")
e
there isn't a way to interpolate regex in general, due to numbered groups and flags
in this case I'd
Copy code
const val alphaNumHyphenPat = """[0-9A-Za-z\-]"""
val someAlphaNumHyphen = "$alphaNumHyphenPat+".toRegex()
val xAlphaNumHyphen = "[Xx]-$alphaNumHyphenPat+".toRegex()
so they'll all be constant strings after compilation and we're not trying to pretend that regex are reusable
z
Is there a way to keep the syntax highlighting on the
alphaNumHyphenPat
?
e
should be possible with a comment
Copy code
// language=RegExp
or with IntelliJ annotations
Copy code
@Language("RegExp")
z
Oh, that's cool! I've never seen that annotation before
c
Note that you need an explicit dependency on
org.jetbrains:annotations:26.0.2-1
if you want to use the annotation on non-JVM platforms (the Kotlin stdlib depends on an old version where the annotations were JVM-only)