Skip to content

Instantly share code, notes, and snippets.

@tateisu
Created November 23, 2018 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tateisu/27aed23e32b91c156bef56c08cff736c to your computer and use it in GitHub Desktop.
Save tateisu/27aed23e32b91c156bef56c08cff736c to your computer and use it in GitHub Desktop.
small example of using Matcher.region
// 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