Skip to content
This repository was archived by the owner on Jul 8, 2022. It is now read-only.

Commit 2f010b1

Browse files
authored
expose PatternDateFormat regex string (#173)
* expose PatternDateFormat regex string * comment matchingRegexString and add test case * extra-escape in the regex for javascript build target to work
1 parent 9c0c4e3 commit 2f010b1

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

klock/src/commonMain/kotlin/com/soywiz/klock/PatternDateFormat.kt

+8-3
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,10 @@ data class PatternDateFormat @JvmOverloads constructor(
104104
}
105105
}
106106

107-
//val escapedFormat = Regex.escape(format)
108-
internal val rx2: Regex = Regex("^" + regexChunks.mapIndexed { index, it ->
107+
/**
108+
* @return the regular expression string used for matching this format, able to be composed into another regex
109+
*/
110+
fun matchingRegexString() = regexChunks.mapIndexed { index, it ->
109111
if (options.optionalSupport) {
110112
val opens = openOffsets.getOrElse(index) { 0 }
111113
val closes = closeOffsets.getOrElse(index) { 0 }
@@ -117,7 +119,10 @@ data class PatternDateFormat @JvmOverloads constructor(
117119
} else {
118120
it
119121
}
120-
}.joinToString("") + "$")
122+
}.joinToString("")
123+
124+
//val escapedFormat = Regex.escape(format)
125+
internal val rx2: Regex = Regex("^" + matchingRegexString() + "$")
121126

122127

123128
// EEE, dd MMM yyyy HH:mm:ss z -- > Sun, 06 Nov 1994 08:49:37 GMT

klock/src/commonTest/kotlin/com/soywiz/klock/DateTimeTest.kt

+21
Original file line numberDiff line numberDiff line change
@@ -475,4 +475,25 @@ class DateTimeTest {
475475
assertEquals(TimezoneOffset((-15).hours), DateFormat("z").parse("-15:00").offset)
476476
assertEquals(TimezoneOffset(0.hours), DateFormat("z").parse("+00:00").offset)
477477
}
478+
479+
@Test
480+
fun testPatternFormatRegex() {
481+
val dtmilli = 1536379689000L
482+
assertEquals(dtmilli, DateTime(2018, 9, 8, 4, 8, 9).unixMillisLong)
483+
484+
val fmt = DateFormat("EEE, dd MMM yyyy HH:mm:ss z")
485+
val msg = "[Sat, 08 Sep 2018 04:08:09 UTC] Example log message"
486+
val nomsg = "[Sat, 08 Sep 20G8 04:08:09 UTC] Example log message" // 20G8
487+
488+
val logPattern = Regex("""^\[(""" + fmt.matchingRegexString() + """)\] """)
489+
490+
assertTrue(logPattern.containsMatchIn(msg), message = "correct datestamp should match")
491+
assertFalse(logPattern.containsMatchIn(nomsg), message = "incorrect datestamp shouldn't match")
492+
493+
val match = logPattern.find(msg)
494+
assertNotNull(match)
495+
496+
assertEquals(dtmilli, fmt.parseLong(match.groups[1]!!.value), message = "datestamp parsed from log line has correct value")
497+
assertEquals("Example log message", msg.drop(match.value.length), message = "total match length for composed regex")
498+
}
478499
}

0 commit comments

Comments
 (0)