简体   繁体   中英

How to remove the last character from a multiline string?

Example: Consider a String like below:

String a="This line1 has a,b,c,\nThis line2 has d,e,f, \nThis line3 has g,h,i";
System.out.println(a);

Output:

This line1 has a,b,c,                 
This line2 has d,e,f,                        
This line3 has g,h,i

As this is a multiline string, How will I be able to remove last occurring comma of each line here from the output & print an output like below below mentioned?

This line1 has a,b,c                
This line2 has d,e,f                        
This line3 has g,h,i

You could use a regex:

String output = a.replaceAll(",\\s*\n", "\n");

It will replace any sequence of a comma, 0 or more spaces and a newline with just a newline character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM