Home>

I want to use regular expressions in Kotlin and do the following:

"0012" == "12"
// I want to make the above true


When comparing here, we are trying to compare after removing 00 of prefix in "0012" with regular expression.
As a result, it became as follows.

val reg = Regex ("0 * ([0-9] +)")
reg.matchEntire ("00123") ?. groups? .get (1) ?. value == "123"

Is there a way to write this more concisely?
I would be grateful if you could tell me any good way.

  • Answer # 1

    I don't know anything about the language, but as long as I google it,

    "00123" .replace ("^ 0 *". toRegex (), "")


    I think you can replace it like this.

  • Answer # 2

    Do you compare with Int?

    print ("123" .toInt () == "00123" .toInt ())
    // =>true

  • Answer # 3

    It is premised that no symbols are included, but it is embedded in regular expressions.

    val a = "0012"
    val b = "12"
    a.matches (Regex ("0 * $b"))