I tried to replace characters in String which works sometimes and does not work most of the time.
I tried the following:
String t = "[javatag]";
String t1 = t;
String t2 = t;
t.replace("\u005B", "");
t.replace("\u005D", "");
t1.replace("[", "");
t1.replace("]", "");
t2.replace("\\]", "");
t2.replace("\\[", "");
System.out.println(t+" , "+t1+" , "+t2);
The resulting output is still "[javatag] , [javatag] , [javatag]" without the "[" and "]" being replaced.
What should I do to replace those "[" and "]" characters ?
String objects in java are immutable. You can't change them.
You need:
t2 = t2.replace("\\]", "");
replace() returns a new String object.
Edit: Because ... I'm breaking away from the pack
And since this is the case, the argument is actually a regex, and you want to get rid of both brackets, you can use replaceAll() instead of two operations:
t2 = t2.replaceAll("[\\[\\]]", "");
This would get rid of both opening and closing brackets in one fell swoop.
Strings are immutable so
t.replace(....);
does nothing
you need to assign the output to some variable like
t = t.replace(....);
Strings in Java are immutable, meaning you can't change them. Instead, do t1 = t1.replace("]", "");. This will assign the result of replace to t1.
String.replace doesn't work that way. You have to use something like t = t.replace("t", "")
String.replace() returns a new string after replacing the required characters. Hence you need to do it in this way:
String t = "[javatag]";
t = t.replace("[","");
t = t.replace("]","");
t.replace(....);
gives you a String (return a string)
you can reassign the origin variable name to the new string
and the old string will later been garbage-collected
:)
Related
I tried:
mystring.replace("'","");
and also
mystring.replaceAll("[']","");
But none of them work, please show me how to remove that ' from my string.
Are you assinging the result of this method? You should be calling it like this :
mystring = mystring.replace("'","");
Strings in Java are immutable - when you call replace, it doesn't change the contents of the existing string - it returns a new string with the modifications. So you want:
This is why you have to assign the return value to a string.
As a note, this also applies to all methods in String. Methods like toUpperCase() return the new string. It does not change the existing.
First, for better help faster please post an MCVE. Next, Java String is immutable, so you must update the mystring reference. Something like,
String mystring = "Papa John's";
mystring = mystring.replace("'","");
System.out.println(mystring);
Output is (as requested) without '
Papa Johns
So, I'm trying to parse a String input in Java that contains (opening) square brackets. I have str.replace("\\[", ""), but this does absolutely nothing. I've tried replaceAll also, with more than one different regex, but the output is always unchanged. Part of me wonders if this is possibly caused by the fact that all my back-slash characters appear as yen symbols (ever since I added Japanese to my languages), but it's been that way for over a year and hasn't caused me any issues like this before.
Any idea what I might be doing wrong here?
Strings are immutable in Java. Make sure you re-assign the return value to the same String variable:
str = str.replaceAll("\\[", "");
For the normal replace method, you don't need to escape the bracket:
str = str.replace("[", "");
public String replaceAll(String regex, String replacement)
As shown in the code above, replaceAll method expects first argument as regular expression and hence you need to escape characters like "(", ")" etc (with "\") if these exists in your replacement text which is to be replaced out of the string. For example :
String oldString = "This is (stringTobeReplaced) with brackets.";
String newString = oldString.replaceAll("\\(stringTobeReplaced\\)", "");
System.out.println(newString); // will output "This is with brackets."
Another way of doing this is to use Pattern.quote("str") :
String newString = oldString.replaceAll(Pattern.quote("(stringTobeReplaced)"), "");
This will consider the string as literal to be replaced.
As always, the problem is not that "xxx doesn't work", it is that you don't know how to use it.
First things first:
a String is immutable; if you read the javadoc of .replace() and .replaceAll(), you will see that both specify that a new String instance is returned;
replace() accepts a string literal as its first argument, not a regex literal.
Which means that you probably meant to do:
str = str.replace("[", "");
If you only ever do:
str.replace("[", "");
then the new instance will be created but you ignore it...
In addition, and this is a common trap with String (the other being that .matches() is misnamed), in spite of their respective names, .replace() does replace all occurrences of its first argument with its second argument; the only difference is that .replaceAll() accepts a regex as a first argument, and a "regex aware" expression as its second argument; for more details, see the javadoc of Matcher's .replaceAll().
For it to work it has to be inside a method.
for example:
public class AnyClass {
String str = "gtrg4\r\n" + "grtgy\r\n" + "grtht\r\n" + "htrjt\r\n" + "jtyjr\r\n" + "kytht";
public String getStringModified() {
str.replaceAll("\r\n", "");
return str;
}
}
I'm trying to do something seemingly simple. I have meta-data with this format
-key=value
I've already split the string at the = but I need to take the - off. I'm trying to use this function key.replaceFirst("-", ""); but it doesn't do anything to the string.
I've tried putting \\ in the regex but that solved nothing.
Solution:
I did not say key = key.replaceFirst("-", "");
You need to assign back return value of replaceFirst as String is immutable object:
key = key.replaceFirst("-", "");
String.replaceFirst does not replace the string in-place, but returns a replaced string.
You need to assign back the return value:
key = key.replaceFirst("-", "");
You are not assigning the string back to it !
key = key.replaceFirst("-", "");
System.out.println(key);
HTH,
Keshava.
I have the following String (it is variable, but classpath is always the same):
C:.Users.mho.Desktop.Eclipse.workspace.GIT.BLUBB...bin.de.test.class.mho.communication.InterfaceXmlHandler
and I want to get just
de.test.class.mho.communication.InterfaceXmlHandler
out of this string. The end
InterfaceXmlHandler
is variable, also the beginning before 'de' and the path itself is variable too, but
de.test.class.mho.
isn't variable.
Why not just use
String result = str.substring(str.lastIndexOf("de.test.class.mho."));
Instead of splitting you could get rid of the beginning of the string:
String input = "C:.Users.mho.Desktop.Eclipse.workspace.GIT.BLUBB...bin.de.test.class.mho.communication.InterfaceXmlHandler";
String output = input.replaceAll(".*(de\\.test\\.class\\.mho.*)", "$1");
You can create a string-array with String.split("de.test.class.mho."). The Array will contain two Strings, the second String will be what you want.
String longString = ""; //whatever
String[] urlArr = longString.split("de.test.class.mho.");
String result;
if(urlArr.length > 1) {
result = "de.test.class.mho." urlArr[1]; //de.test.class.mho.whatever.whatever.whatever
}
You can use replaceAll() to "extract" the part you want:
String part = str.replaceAll(".*(?=de\\.test\\.class\\.mho\\.)", "");
This uses a look-ahead to find all characters before the target, and replace them with a blank (ie delete them).
You could quite reasonably ignore escaping the dots for brevity:
String part = str.replaceAll(".*(?=de.test.class.mho.)", "");
I doubt it would give a different result.
I want to remove any substring(s) in a string that begins with 'galery' and ends with 'jssdk));'
For instance, consider the following string:
Galery something something.... jssdk));
I need an algorithm that removes 'something something....' and returns 'Galery jssdk));'
This is what I've done, but it does not work.
newsValues[1].replaceAll("Galery.*?jssdK));", "");
Could probably be improved, I've done it fast:
public static String replaceMatching(String input, String lowerBound, String upperBound{
Pattern p = Pattern.compile(".*?"+lowerBound+"(.*?)"+upperBound+".*?");
Matcher m = p.matcher(input);
String textToRemove = "";
while(m.find()){
textToRemove = m.group(1);
}
return input.replace(textToRemove, "");
}
UPDATE Thx for accepting the answer, but here is a smaller reviewed version:
public static String replaceMatching2(String input, String lowerBound, String upperBound){
String result = input.replaceAll("(.*?"+lowerBound + ")" + "(.*?)" + "(" + upperBound + ".*)", "$1$3");
return result;
}
The idea is pretty simple actually, split the String into 3 groups, and replace those 3 groups with the first and third, droping the second one.
You are almost there, but that will remove the entire string. If you want to remove anything between Galery and jssdK));, you will have to do something like so:
String newStr = newsValues[1].replaceAll("(Galery)(.*?)(jssdK\\)\\);)","$1$3");
This will put the strings into groups and will then use these groups to replace the entire string. Note that in regex syntax, the ) is a special character so it needs to be escaped.
String str = "GaleryABCDEFGjssdK));";
String newStr = str.replaceAll("(Galery)(.*?)(jssdK\\)\\);)","$1$3");
System.out.println(newStr);
This yields: GaleryjssdK));
I know that the solution presented by #amit is simpler, however, I thought it would be a good idea to show you a useful way in which you can use the replaceAll method.
Simplest solution will be to replace the string with just the "edges", effectively "removing" 1 everything between them.
newsValues[1].replaceAll("Galery.*?jssdK));", "GaleryjssdK));");
1: I used "" here because it is not exactly replacing - remember strings are immutable, so it is creating a new object, without the "removed" part.
newsValues[1] = newsValues[1].substring(0,6)+newsValues.substring(newsValues[1].length()-5,newsValues[1].length())
This basically concatenates the "Galery" and the "jssdk" leaving or ignoring everything else. More importantantly, you can simply assign newValues[1] = "Galeryjssdk"