Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract substring between given strings

Tags:

string

kotlin

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.

like image 513
4ndro1d Avatar asked Jul 06 '18 12:07

4ndro1d


People also ask

How can you extract a substring from a given string?

You can extract a substring from a String using the substring() method of the String class to this method you need to pass the start and end indexes of the required substring.

How do I extract text between two delimiters in Excel?

The easiest way to extract a substring between two delimiters is to use the text to column feature in Excel, especially if you have multiple delimiters. In this example, use =MID(A2, SEARCH(“-“,A2) + 1, SEARCH(“-“,A2,SEARCH(“-“,A2)+1) – SEARCH(“-“,A2) – 1) in cell B2 and drag it to the entire data range.


1 Answers

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(';')
like image 191
zsmb13 Avatar answered Sep 19 '22 20:09

zsmb13