Delete last occurrence in string
java, string
Solution
Use regex replace:
public static String deleteLastOccurrence(String original, String target){
return original.replaceAll("(,)?\\b" + target + "\\b.*", "$1" + target);
}
This code also works when the target is the first or last word in the original (hence the regex syntax `\b` which means "word boundary")
Also, rename your method to `deleteAfterFirstOccurrence()`, because your current name is misleading: The "last occurrence" is irrelevant to what you want.
Here's a little test:
public static void main(String[] args) {
// Test for target in middle:
System.out.println(deleteLastOccurrence("foo,bar,dog,cat,dog,bird,dog", "dog"));
// Test for target at start:
System.out.println(deleteLastOccurrence("dog,bar,dog,cat,dog,bird,dog", "dog"));
// Test for target at end:
System.out.println(deleteLastOccurrence("foo,bar,cat,bird,dog", "dog"));
}
Output:
foo,bar,dog
dog
foo,bar,cat,bird,dog
Problem
I am trying to trim a string to the first occurrence of a specific word in a single string of comma separated words. E.g.: ``` deleteLastOccurrence("foo,bar,dog,cat,dog,bird","dog") ``` should return ``` "foo,bar,dog" ``` I have the following, and it doesn't seem to be working correctly: ``` public String deleteLastOccurrence(String original, String target){ String[] arr = original.split(","); arr = Arrays.copyOfRange(arr, Arrays.asList(arr).indexOf(target), original.length()-1); path = StringUtils.join(pathArray,","); } ``` Any suggestions on a simpler method? Thanks in advance...