如何使用Java正则表达式强制某些字符串以新行开头?

时间:2013-11-16 21:57:02

标签: java regex

以下是String details

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

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

我需要对其进行转换,以便StateZip从新行开始

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

这是我试过的

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

1 个答案:

答案 0 :(得分:2)

你几乎做对了,你需要做一些小改动:

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

请注意更改,您需要使用捕获组()捕获值,以便通过$1在替换字符串中使用它们。

这是使用PHP的Regex101 demo,但概念是相同的,请注意现在一切正常。