Skip to content

Instantly share code, notes, and snippets.

@cascer1
Created January 19, 2022 09:15
Show Gist options
  • Save cascer1/68247e271d2e79b4199e981717aea0c7 to your computer and use it in GitHub Desktop.
Save cascer1/68247e271d2e79b4199e981717aea0c7 to your computer and use it in GitHub Desktop.
import java.util.regex.Pattern
var texts = listOf(
"""
```
remove this
```
""".trimIndent(),
"""
`remove this`
""".trimIndent(),
"""something must be `removed ` but not everything""",
"""
```
remove this
`
```
""".trimIndent(),
"""
```
remove this
\`
```
""".trimIndent(),
"""\`keep this\`""",
"""\`keep this`""",
"""
\``
partial remove?
\```
""".trimIndent(),
"""
\`\`\`
keep all
\`\`\`
""".trimIndent()
)
val monospacePattern: Pattern = Pattern.compile("`[^`]+`")
texts.forEach { inputText ->
println("\n=================\n")
println(inputText)
var thisMessage = inputText.replace("\\`", "")
thisMessage = monospacePattern.matcher(thisMessage).replaceAll("")
var inBlock = false
val newLines = ArrayList<String>()
thisMessage.lines().forEachIndexed { index, line ->
val thisLine = line.replace("\\`", "")
if (thisLine.contains("```")) {
if (!inBlock) {
// we're starting a new block, ignore everything after the ticks
newLines.add(line.substringBefore("```"))
} else {
newLines.add(line.substringAfter("```"))
}
inBlock = !inBlock
} else {
if (!inBlock) {
newLines.add(thisLine)
}
}
}
println("--- REPLACED WITH ---")
newLines.forEach { println(it) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment