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



>这是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) {}

你几乎做对了,你需要小的修改:

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

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

这是一个使用 PHP 的正则表达式 101 演示,但概念是相同的,请注意现在一切如何正常工作。

最新更新