barroco
barroco

Reputation: 3108

string transformation with regex

I have the following string:

val s1:String = "1. my line 1\n2. my other line\n3. my 3rd line\n4. and so on"

Now, I want transform at other:

val s2:String = "<b>1. </b>my line 1\n<b>2. </b>my other line\n<b>3. </b>my 3rd line\n<b>4. </b>and so on"

What is better way to do it?

Upvotes: 0

Views: 303

Answers (1)

sepp2k
sepp2k

Reputation: 370112

s1.replaceAll("""(?m)^(\d+\. )""", "<b>$1</b>")

Read: Find all occurences of "beginning of the line followed by one or more digits followed by a dot followed by a space" and replace them with the matched substring surrounded by <b> and </b>.

The (?m) bit makes it so that ^ means "beginning of line" instead of "beginning of string". The """ are so that there's no need to double escape.

Upvotes: 3

Related Questions