Skip to content

Instantly share code, notes, and snippets.

@rahul-lohra
Created July 19, 2020 12:20
Show Gist options
  • Save rahul-lohra/a66c4a57ab481fe8fc74a8a0880946e8 to your computer and use it in GitHub Desktop.
Save rahul-lohra/a66c4a57ab481fe8fc74a8a0880946e8 to your computer and use it in GitHub Desktop.
Dollar replace logic
fun replaceDollar(inputString: String):String{
var finalText = inputString
val indexesToIgnore = hashSetOf<Int>()
val patternsToIgnore = arrayListOf("\\$\\$","\\$\\{\"\\$\"}")
patternsToIgnore.forEach {
val doubleDollarPattern = Pattern.compile(it)
val matcher = doubleDollarPattern.matcher(inputString)
while (matcher.find()) {
val startIndex = matcher.start()
val endIndex = matcher.end()
for (i in startIndex..endIndex) {
indexesToIgnore.add(i)
}
}
}
val replaceValue = "\${\"$\"}"
val dollarRegex = "\\$"
val dollarLength = 1
val dollarPattern = Pattern.compile(dollarRegex)
val dollarMatcher = dollarPattern.matcher(inputString)
var replaceCount = 0
while (dollarMatcher.find()) {
val startIndex = dollarMatcher.start()
if (!indexesToIgnore.contains(startIndex)) {
val offset = replaceCount * (replaceValue.length - dollarLength)
finalText = finalText.replaceRange(startIndex + offset, startIndex + offset + dollarLength, replaceValue)
replaceCount += 1
}
}
return finalText
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment