7

I'm trying to replace the last dot in a String using a regular expression.

Let's say I have the following String:

String string = "hello.world.how.are.you!";

I want to replace the last dot with an exclamation mark such that the result is:

"hello.world.how.are!you!"

I have tried various expressions using the method String.replaceAll(String, String) without any luck.

4 Answers 4

14

One way would be:

string = string.replaceAll("^(.*)\\.(.*)$","$1!$2");

Alternatively you can use negative lookahead as:

string = string.replaceAll("\\.(?!.*\\.)","!");

Regex in Action

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot! I would never have come up with that monster.
The fact that it's a monster (your words, not mine) is probably a good argument for not using it :-) Still, if it works, it should be accepted since you did ask for a regex solution.
I'm greedy as the pattern and I approve :) Nice use of greedy .*
Why not make the second quantifier reluctant, as in ^(.*)\\.(.*?)$ ?
10

Although you can use a regex, it's sometimes best to step back and just do it the old-fashioned way. I've always been of the belief that, if you can't think of a regex to do it in about two minutes, it's probably not suited to a regex solution.

No doubt get some wonderful regex answers here. Some of them may even be readable :-)

You can use lastIndexOf to get the last occurrence and substring to build a new string: This complete program shows how:

public class testprog {
    public static String morph (String s) {
        int pos = s.lastIndexOf(".");
        if (pos >= 0)
            return s.substring(0,pos) + "!" + s.substring(pos+1);
        return s;
    }
    public static void main(String args[]) {
        System.out.println (morph("hello.world.how.are.you!"));
        System.out.println (morph("no dots in here"));
        System.out.println (morph(". first"));
        System.out.println (morph("last ."));
    }
}

The output is:

hello.world.how.are!you!
no dots in here
! first
last !

2 Comments

Yeah I had a solution using StringBuilder and replacing based on the index of the last dot. But I wanted to get it done using a regular expression if possible hence the question.
Just as an FYI, my previous solution using StringBuilder looked like this: StringBuilder builder = new StringBuilder(string); builder.replace(lastDotIndex, lastDotIndex + 1, "!"); String newString = builder.toString();
7

The regex you need is \\.(?=[^.]*$). the ?= is a lookahead assertion

"hello.world.how.are.you!".replace("\\.(?=[^.]*$)", "!")

Comments

1

Try this:

string = string.replaceAll("[.]$", "");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.