以下是String details
String details;
System.out.println(details); // gives the following :
"Address: 100 Main Street
City: CHICAGO State: IL Zip: 624324
Department ID: 890840809 ........
........................ "
我需要对其进行转换,以便State
和Zip
从新行开始
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) {}
答案 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,但概念是相同的,请注意现在一切正常。