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

Commit

Permalink
expose PatternDateFormat regex string (#173)
Browse files Browse the repository at this point in the history
* expose PatternDateFormat regex string

* comment matchingRegexString and add test case

* extra-escape in the regex for javascript build target to work
  • Loading branch information
alexbobp authored Jul 17, 2021
1 parent 9c0c4e3 commit 2f010b1
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,10 @@ data class PatternDateFormat @JvmOverloads constructor(
}
}

//val escapedFormat = Regex.escape(format)
internal val rx2: Regex = Regex("^" + regexChunks.mapIndexed { index, it ->
/**
* @return the regular expression string used for matching this format, able to be composed into another regex
*/
fun matchingRegexString() = regexChunks.mapIndexed { index, it ->
if (options.optionalSupport) {
val opens = openOffsets.getOrElse(index) { 0 }
val closes = closeOffsets.getOrElse(index) { 0 }
Expand All @@ -117,7 +119,10 @@ data class PatternDateFormat @JvmOverloads constructor(
} else {
it
}
}.joinToString("") + "$")
}.joinToString("")

//val escapedFormat = Regex.escape(format)
internal val rx2: Regex = Regex("^" + matchingRegexString() + "$")


// EEE, dd MMM yyyy HH:mm:ss z -- > Sun, 06 Nov 1994 08:49:37 GMT
Expand Down
21 changes: 21 additions & 0 deletions klock/src/commonTest/kotlin/com/soywiz/klock/DateTimeTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -475,4 +475,25 @@ class DateTimeTest {
assertEquals(TimezoneOffset((-15).hours), DateFormat("z").parse("-15:00").offset)
assertEquals(TimezoneOffset(0.hours), DateFormat("z").parse("+00:00").offset)
}

@Test
fun testPatternFormatRegex() {
val dtmilli = 1536379689000L
assertEquals(dtmilli, DateTime(2018, 9, 8, 4, 8, 9).unixMillisLong)

val fmt = DateFormat("EEE, dd MMM yyyy HH:mm:ss z")
val msg = "[Sat, 08 Sep 2018 04:08:09 UTC] Example log message"
val nomsg = "[Sat, 08 Sep 20G8 04:08:09 UTC] Example log message" // 20G8

val logPattern = Regex("""^\[(""" + fmt.matchingRegexString() + """)\] """)

assertTrue(logPattern.containsMatchIn(msg), message = "correct datestamp should match")
assertFalse(logPattern.containsMatchIn(nomsg), message = "incorrect datestamp shouldn't match")

val match = logPattern.find(msg)
assertNotNull(match)

assertEquals(dtmilli, fmt.parseLong(match.groups[1]!!.value), message = "datestamp parsed from log line has correct value")
assertEquals("Example log message", msg.drop(match.value.length), message = "total match length for composed regex")
}
}

0 comments on commit 2f010b1

Please sign in to comment.