Search code examples
androidstringkotlinmobile

How can i check if my string resource has a placeholder? Kotlin


I have a list of string resources, i want to display them but i want to check for string res that have place holders in them, so that i can replace the placeholders with string values

<string name="app_name">Its a poem right?</string>
<string name="app_name">We are %1$s to the see the queen, are you %1$s</string>
<string name="app_name">where are we %s</string>

I want to be able to fill the place holders with this text in my fragment var going = "goin"


Solution

  • I solved the issue by creating a string extension

    fun String.containsPlaceholderRegex(): Boolean {
      val placeholderRegex = Regex("%([0-9]+\\$)?[a-zA-Z]")
      return placeholderRegex.containsMatchIn(this)
    }
    

    then you can check if the string has a placeholder by below.

    stringPropertyName.containsPlaceholderRegex()