28

Given the following string: be_de=Interessant für Dich; be_fr=Intéressant pour toi;

What is the nicest way to extract the substring for a given locale in Kotlin? e.g. I have given the locale be_fr I want to have Intéressant pour toi as a result. The string is always in between the locale followed by a = and a ;

There could be more locales with strings given, and the position of the value to extract always varies.

Of course I could just create a substring after the first index of my locale and then search for the fist index of the semicolon, but I assume there is a more elegant way like using removeSurrounding, which I can't think of atm.

2
  • Have you think using a different encoding like JSON or .properties file? It will be more suited for this kind of purposes. Commented Jul 6, 2018 at 14:31
  • See this youtrack issue. Commented Oct 12, 2021 at 16:47

2 Answers 2

79

I don't think removeSurrounding applies here, as you can only remove text with that if you know exactly the entire prefix and suffix to remove.

I'd go with this, as it's very easy to read:

val result = data.substringAfter("be_fr=").substringBefore(';')
Sign up to request clarification or add additional context in comments.

1 Comment

actually it could be val result = data.substringAfter("be_fr=", "").substringBefore(";", "") - empty strings means that if delimiter e.g. be_fr= is missing than the result will be an empty string. Otherwise you'll get origin string, which is astonishing behaviour for me.
0
val s = "be_de=Interessant für Dich; be_fr=Intéressant pour toi;"
val result = s.substringAfter("be_fr=", "").substringBefore(";")
println(result)

Intéressant pour toi

Notice that I use ("be_fr=", "").

If the sample doesn't contain be_fr= you will get an empty string. If you use the solution of @zsmb13 you will get be_de=Interessant für Dich.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.