How to replace last dot in a string using a regular expression?

后端 未结 4 1189
小蘑菇
小蘑菇 2021-01-05 09:25

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         


        
4条回答
  •  孤独总比滥情好
    2021-01-05 10:08

    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 !
    

提交回复
热议问题