Home > front end >  How Unescape the already escaped string in kotlin?(Android)
How Unescape the already escaped string in kotlin?(Android)

Time:10-26

How to convert an already Enscaped string to unescape in android

// To convert from normal to enscaped string
val escaped:String = Regex.escape("")

but there is no Unescape function in Regex

CodePudding user response:

Here example code that solve your problem:

import java.lang.StringBuilder

fun main(args: Array<String>) {
    val literal = "a\\Qb\\Ec"
    val str = Regex.escape(literal)

    val newValue = unescape(str)
    
    println(literal)
    println(str)
    println(newValue)
}

enum class S { BEGIN, ESC, LITERAL, ESC_END }

fun unescape(str: String): String {
    val sb = StringBuilder()
    var state = S.BEGIN
    for (c in str.toCharArray()) {
        when (c) {
            '\\' ->
                when (state) {
                    S.BEGIN -> {
                        state = S.ESC
                    }

                    S.LITERAL -> {
                        state = S.ESC_END
                    }

                    S.ESC -> {
                        state = S.ESC
                        sb.append("\\")
                    }

                    S.ESC_END -> {
                        state = S.LITERAL
                        sb.append("\\\\")
                    }
                }

            'Q' ->
                when (state) {
                    S.ESC -> state = S.LITERAL
                    S.BEGIN -> {
                        sb.append(c)
                    }

                    S.LITERAL -> {
                        sb.append(c)
                    }

                    S.ESC_END -> {
                        state = S.LITERAL
                        sb.append("\\Q")
                    }
                }

            'E' ->
                when (state) {
                    S.ESC -> {
                        state = S.BEGIN
                        sb.append("E")
                    }
                    S.BEGIN -> {
                        sb.append(c)
                    }

                    S.LITERAL -> {
                        sb.append(c)
                    }

                    S.ESC_END -> {
                        state = S.BEGIN
                    }
                }

            else -> {
                sb.append(c)
            }
        }
    }
    return sb.toString()
}
  • Related