Created
July 19, 2020 12:20
-
-
Save rahul-lohra/a66c4a57ab481fe8fc74a8a0880946e8 to your computer and use it in GitHub Desktop.
Dollar replace logic
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
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