Home > Enterprise >  Loop Through a String and Replace Full Stops with a New Line in Kotlin
Loop Through a String and Replace Full Stops with a New Line in Kotlin

Time:11-02

I have some cooking instructions obtained as an API response but it is in prose (sample below). I need to format and put a new line for every full stop(.) in the sentense.

"Put the flour, eggs, milk, 1 tbsp oil and a pinch of salt into a bowl or large jug, then whisk to a smooth batter. Set aside for 30 mins to rest if you have time, or start cooking straight away.\r\nSet a medium frying pan or crêpe pan over a medium heat and carefully wipe it with some oiled kitchen paper. When hot, cook your pancakes for 1 min on each side until golden, keeping them warm in a low oven as you go.\r\nServe with lemon wedges and sugar, or your favourite filling.

I am working with the below code but it is not putting the new line/ line break after the full stop.

val input = meal.directions
val formattedDirections = input.replace("\\.\\s?", "\\.\n")

I have looked around similar questions posted for Python, Java, JavaScript, PHP and C but I can't find a way out.

Anyone with the Algorithm/Regex or a lead please help

CodePudding user response:

replace method itself replaces all occurrences and not just one occurrence.

But if you specify a string literal as first argument, it only literally replaces that string even if it contains a regex.

To treat first argument as a regex, you need to convert it to a regex object by either calling .toRegex() method on string literal or by creating an object of Regex. Sample code following,

val formattedDirections = input.replace("\\.\\s?".toRegex(), "\\.\n")

OR

val formattedDirections = input.replace(Regex("\\.\\s?"), "\\.\n")
  • Related