Created
November 23, 2018 06:59
-
-
Save tateisu/27aed23e32b91c156bef56c08cff736c to your computer and use it in GitHub Desktop.
small example of using Matcher.region
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// small example of using Matcher.region | |
val text = "ABC*DEF*(GHI)*JKL*" | |
val matchers = arrayOf( | |
Pattern.compile("""^\*.+?\*""").matcher(text), | |
Pattern.compile("""\A\(.+?\)""").matcher(text) | |
) | |
matchers.forEach { it.useAnchoringBounds(true) } | |
fun <T, V> Array<out T>.firstNonNull(predicate: (T) -> V?): V? { | |
for (element in this) return predicate(element) ?: continue | |
return null | |
} | |
var i = 0 | |
var end = text.length | |
while (i < end) { | |
val m = matchers.firstNonNull { | |
it.region(i, end) | |
if (it.find()) { | |
it | |
} else { | |
null | |
} | |
} | |
if (m == null) { | |
++i | |
} else { | |
println(m.group()) | |
i = m.end() | |
} | |
} | |
/* | |
output: | |
*DEF* | |
(GHI) | |
*JKL* | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment