user1114509
user1114509

Reputation: 259

Conditionally replacing the last characters of a string

I have a string, say xyzabc_1_1.

I want to first test if the last characters are _1 and if so, replace the last _1 with _01_1. The string will become xyzabc_1_01_1.

For finding if the last digits are _1 I'm using

str1.matches("^.*_\\d$")

But don't know the second part, i.e. how to replace the last occurrence with _01_1.

Upvotes: 2

Views: 2820

Answers (4)

Bohemian
Bohemian

Reputation: 424963

This is a simple one-liner, using replaceAll() and back-references:

String str2 = str1.replaceAll("_\\d$", "_01$0");

It's not clear if the 01 is based on the 1 or is a constant. ie if 2 were to become 02_2 then do this instead: str1.replaceAll("_(\\d)$", "_0$1_$1")

Here's a test:

String str1 = "xyzabc_1_1";
String str2 = str1.replaceAll("_\\d$", "_01$0");
System.out.println(str2);

Output:

xyzabc_1_01_1

Upvotes: 2

user1114509
user1114509

Reputation: 259

Done but needs optimization...

String str1 = "xyzabc_1";

    /* System.out.println(str1.matches("^.*_\\d$")); */

    try {
        if (str1.matches("^.*_\\d$")) {
            String cutted = str1.substring(str1.lastIndexOf("_"),
                    str1.length());
            str1 = str1.replaceAll(cutted, "_01" + cutted); //
            System.out.println(str1);
        } else {

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

Upvotes: 0

Rob Hruska
Rob Hruska

Reputation: 120286

To replace the string, you can just grab a substring and concatenate your new suffix. Additionally, you can use endsWith instead of the regular expression. IMHO it's more readable.

public String replaceSuffix (String target) {
    if (!target.endsWith("_1")) {
       return target;
    }

    return target.substring(0, target.length() - 2) + "_01_1";
}

And just for the fun of it, here's a more reusable version for replacing different things:

public String replaceSuffix (String target, String suffix, String replacement) {
    if (!target.endsWith(suffix)) {
        return target;
    }

    String prefix = target.substring(0, target.length() - suffix.length());
    return prefix + replacement;
}

Invoked as (for your specific example):

String replaced = replaceSuffix("xyzabc_1_1", "_1", "_01_1");

Depending on your expected input, you might also want some null/empty/length checks on str.

Upvotes: 4

Caffeinated
Caffeinated

Reputation: 12484

You'd rather replace the whole string with the new one. Create a new string with the '_01_1' concatenated. Then replace.

Upvotes: 0

Related Questions