Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Regex to replace all ocurrences of an empty string except last one

809259Nov 15 2010 — edited Nov 15 2010
Hello, everybody!

I need to come up with a regex to replace all ocurrences of an empty string except the last one. Right now I'm doing this with this code:
public static void main(String[] args)
{
    String str = "abc";
    String regex = "";
    System.out.println(str.replaceAll(regex, "-").replaceFirst("-$", "")); // -a-b-c
}
As you can see, to do this I have to make two calls: one for replaceAll and another for replaceFirst to get rid of the last character. So I would like to get rid of the call to replaceFirst and have the regex variable to be an regex that would insert the character along all the string except the last one. I'm really not very good with regexs, so I'm asking your help here. The thing that I have is working, but I think it would be more elegant with just one regex to do it.

Thank you in advance.

Marcos
This post has been answered by 791266 on Nov 15 2010
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 13 2010
Added on Nov 15 2010
4 comments
410 views