简体   繁体   中英

How to Remove string after second last occurrence of special character?

In my application I am trying to make breadcrumbs using StringBuilder

Suppose this is the string :

String1>String2>String3>String4>String5>

Now I want to remove String5> and I want string like this:

String1>String2>String3>String4>

How can I do this?

Please help!!

you can use regex \\\\w+>$

\\\\w+ mean match [a-zA-Z0-9_]

>$ match > character where $ mean at the end

Regex Demo Link

    String s  = "String1>String2>String3>String4>String5>";
    String s2 = s.replaceAll("\\w+>$","");
    System.out.println(s2);

Output :

String1>String2>String3>String4>

Note : To avoid _ use

    String s2 = s.replaceAll("[a-zA-Z\\d]+>$","");

Just in case if you have data with some special characters like

String s = "String1>Stri$#$ng2>String3>Stri#$$#ng4>St$#:/|ring5>";

then above solution won't work so you can use

    String s2 = s.replaceAll("[^>]+>$","");
    // s2 will be = String1>Stri$#$ng2>String3>Stri#$$#ng4>

Regex Demo Link

[^>]+ : ^ inside [] works as negation mean match everything except > character

Split string by > and then apply for loop on the array. match string by position. if match then delete otherwise add to new stringBuilder.

You can use combination of lastIndexOf and substring().

Example:

String oldValue = "String1>String2>String3>String4>String5>";
int lastIndex = oldValue.lastIndexOf('>', oldValue.length() - 2);
String newValue = oldValue.substring(0, lastIndex + 1);

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