Azamat Bagatov
Azamat Bagatov

Reputation: 289

How to force certain strings start with a new line using Java regex?

Here is the String details

String details;
System.out.println(details); // gives the following :

                                "Address: 100 Main Street
                                City: CHICAGO            State: IL       Zip: 624324
                                Department ID: 890840809 ........
                               ........................  "

I need to transform it so that State and Zip start from a new line

Address: 100 Main Street
City: CHICAGO            
State: IL       
Zip: 624324
Department ID: 890840809 ........

Here is what i tried

try {details = details.replaceAll(" State:.*", "\nState:.*"); 
} catch (Exception e) {}
try {details = details.replaceAll(" Zip:.*", "\nZip:.*"); 
} catch (Exception e) {}

Upvotes: 0

Views: 42

Answers (1)

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

You almost got it right, you need minor modifications:

try {details = details.replaceAll(" State:(.*)", "\nState:$1");
                                          ^^^^            ^^ 
} catch (Exception e) {}
try {details = details.replaceAll(" Zip:(.*)", "\nZip:$1");
                                        ^^^^          ^^
} catch (Exception e) {}

Notice the changes, you need to capture the values using capturing groups () so you can use them in the replacement string via $1.

Here is a Regex101 demo using PHP but the concepts are the same, notice how everything works fine now.

Upvotes: 2

Related Questions