String replace all special characters in the end
Am very poor in regex, so please bear with me. I have strings LQiW0/QIDAQAB/ and LQiW0/QIDAQAdfB/ . I’m trying to remove the last forward slash. Tried str= str.replaceAll(«\\/»,»»); I tried replace all but it replaces all forward slashes.. and the thing is, I want to replace if it is at last position
5 Answers 5
$ means end of line (in this case, end of string).
@fge, I wrote in this case, end of string in my answer. If that was not clear, could you edit my answer? (I’m not good at English writing.)
Do you really need regex? A simple substring will do the job:
str = str.substring(0, str.lastIndexOf("/"));
But, if you want to replace the forward slash only if it is the end of the string, then replaceAll would be good there.
But you can also use this (This might not be more readable compared to replaceAll ):
str = str.endsWith("/") ? str.substring(0, str.length() - 1) : str;
@Baadshah. Do you want to keep everything after that too? You mean you just want to remove the last / ?
It’s better not to use regex replacements for these trivial operations. People tend to use regular expressions all the time even when they are not needed. Also, regular expressions can be very straight forward but get ugly pretty fast when you need to cover some side cases. See https://softwareengineering.stackexchange.com/questions/113237/when-you-should-not-use-regular-expressions
In your case there’s a good tool for the job.
You can use org.apache.commons.lang.StringUtils
StringUtils.stripEnd("LQiW0/QIDAQAdfB/", "/") = "LQiW0/QIDAQAdfB" StringUtils.stripEnd("LQiW0/QIDAQAdfB///", "/") = "LQiW0/QIDAQAdfB" StringUtils.stripStart("///LQiW0/QIDAQAdfB/", "/") = "LQiW0/QIDAQAdfB/" StringUtils.stripStart("///LQiW0/QIDAQAdfB///", "/") = "LQiW0/QIDAQAdfB///"
Replace the last part of a string
Have you considered rewriting your loop so the right amount of commas show up? I’ve seen a Stackoverflow question for getting exactly that loop as efficient as possible.
11 Answers 11
The following code should replace the last occurrence of a ‘,’ with a ‘)’ .
StringBuilder b = new StringBuilder(yourString); b.replace(yourString.lastIndexOf(","), yourString.lastIndexOf(",") + 1, ")" ); yourString = b.toString();
Note This will throw Exceptions if the String doesn’t contain a ‘,’ .
10x, didn’t know that. I think that your solution will replace any last , and not only if it’s in the end of the string.
Dani: StringBuilder in Java is the non-thread safe variant of StringBuffer which makes it noticeably faster (if I remember correctly, about 20-30%) and should be preferred if the thread safe StringBuffer isn’t explicitly needed.
heh. thats sick. i thought that was C# at first. only difference is the capitalization of the methods, really.
You can use a regular expression:
String aResult = "Insert into dual (name,date,".replaceAll(",$", ")");
replaceAll(. ) will match the string with the given regular expression (parameter 1) (in this case we match the last character if it is a comma). Then replace it with a replacement (parameter 2) (in this case is ‘ ) ‘).
Plus! If you want to ensure that trailing spaces and tabs are taken care of, you can just change the regular expression to ‘ ,\[ \t\]*$ ‘. Note: ‘ \[ ‘ and ‘ \] ‘ is without backslash (I don’t know how to properly escape it).
If you use replaceAll(«,$», «)») as replaceAll(«[,]*$», «)») , it will work although it has several commas. For ex; » (name, date. » —> » (name, date)». I think this is more flexible.
This is a custom method to replace only the last substring of a given string. It would be useful for you:
private String replaceLast(String string, String from, String to)
str = str.substring(0, str.lastIndexOf(",")) + ")";
StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
The more readable way . Which you can use to learn about String and its functions
String myString = "Insert into dual (name,date,"; String newString = ""; int length = myString.length(); String lastChar = myString.substring(length-1); if (lastChar.contains(",")) < newString = myString.substring(0,length-1) + ")"; >System.out.println(newString);
Check the length of the string, check the last character (if you have the length it is easy), and replace it — when necessary.
This solution is not language-specific — just use common sense.
On a similar search I found this answer:
I think it is the best, because it uses the Java methods as intended rather than trying to reinvent the wheel.
It essentially reads the string backwards and uses the String object’s replaceFirst method, this is exactly what I was looking for.
Here is the documentation on replaceFirst String method and the StringBuffer’s reverse function:
Here is how I implemented it to simply remove some HTML ‘pre’ tags from a code snippet that I wanted to interpret. Remember to reverse your search string as well, and then reverse everything back to normal afterwards.
private String stripHtmlPreTagsFromCodeSnippet(String snippet) < String halfCleanSnippet = snippet.replaceFirst("
", ""); String reverseSnippet = new StringBuffer(halfCleanSnippet).reverse().toString(); String reverseSearch = new StringBuffer("").reverse().toString(); String reverseCleanSnippet = reverseSnippet.replaceFirst(reverseSearch, ""); return new StringBuffer(reverseCleanSnippet).reverse().toString(); >
java replaceLast() [duplicate]
Is there replaceLast() in Java? I saw there is replaceFirst() . EDIT: If there is not in the SDK, what would be a good implementation?
People here are way too eager to mark questions duplicates. This question (general replaceAll()) has nothing to do with the question in the «duplicate».
12 Answers 12
It could (of course) be done with regex:
public class Test < public static String replaceLast(String text, String regex, String replacement) < return text.replaceFirst("(?s)"+regex+"(. *?"+regex+")", replacement); >public static void main(String[] args) < System.out.println(replaceLast("foo AB bar AB done", "AB", "--")); >>
although a bit cpu-cycle-hungry with the look-aheads, but that will only be an issue when working with very large strings (and many occurrences of the regex being searched for).
A short explanation (in case of the regex being AB ):
(?s) # enable dot-all option A # match the character 'A' B # match the character 'B' (?! # start negative look ahead .*? # match any character and repeat it zero or more times, reluctantly A # match the character 'A' B # match the character 'B' ) # end negative look ahead
EDIT
Sorry to wake up an old post. But this is only for non-overlapping instances. For example .replaceLast(«aaabbb», «bb», «xx»); returns «aaaxxb» , not «aaabxx»
True, that could be fixed as follows:
public class Test < public static String replaceLast(String text, String regex, String replacement) < return text.replaceFirst("(?s)(.*)" + regex, "$1" + replacement); >public static void main(String[] args) < System.out.println(replaceLast("aaabbb", "bb", "xx")); >>
Replace the last occurrence of a string in another string [duplicate]
Neither string.replace() nor string.replaceFirst() would do the job. Is there a string.replaceLast()? And, If not, will there ever be one or is there an alternative also working with regexes?
7 Answers 7
Find the index of the last occurrence of the substring.
String myWord = "AAAAAasdas"; String toReplace = "AA"; String replacement = "BBB"; int start = myWord.lastIndexOf(toReplace);
Create a StringBuilder (you can just concatenate Strings if you wanted to).
StringBuilder builder = new StringBuilder();
Append the part before the last occurrence.
builder.append(myWord.substring(0, start));
Append the String you want to use as a replacement.
Append the part after the last occurrence from the original `String.
builder.append(myWord.substring(start + toReplace.length()));
myWord = myWord.replaceAll("AA$","BB");
It doesn’t work if string has question mark (?). For example: StringUtil.replaceLast(«ab?c», «b?c», «») returns ab? instead of a
Just get the last index and do an in place replacement of the expression with what you want to replace.
myWord is the original word say AABDCAADEF . sourceWord is what you want to replace, say AA targetWord is what you want to replace it with say BB .
StringBuilder strb=new StringBuilder(myWord); int index=strb.lastIndexOf(sourceWord); strb.replace(index,sourceWord.length()+index,targetWord); return strb.toString();
This is useful when you want to just replace strings with Strings.A better way to do it is to use Pattern matcher and find the last matching index. Take as substring from that index, use the replace function there and then add it back to the original String. This will help you to replace regular expressions as well