This question already has answers here:
String replace method is not replacing characters
(5 answers)
Closed 7 years ago.
I want the text "REPLACEME" to be replaced with my StringBuffer symbols. When I print symbols, it is a valid string. When I print my query, it still has the text REPLACEME instead of symbols. Why?
private String buildQuery(){
String query = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(REPLACEME)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
deserializeQuotes();
StringBuffer symbols = new StringBuffer();
for(int i = 0; i < quotes.size();i++){
if(i == (quotes.size()-1))
symbols.append("%22" + quotes.get(i).getSymbol() + "%22%"); //end with a quote
else
symbols.append("%22" + quotes.get(i).getSymbol() + "%22%2C");
}
System.out.println("***SYMBOLS***" + symbols.toString());
query.replaceAll("REPLACEME", symbols.toString());
return query;
}
Change
query.replaceAll("REPLACEME", symbols.toString());
to:
query = query.replaceAll("REPLACEME", symbols.toString());
Strings in Java are designed to be immutable.
That is why replaceAll() can't replace the characters in the current string, so it must return a new string with the characters replaced.
Also if you want to simply replace literals and don't need regex syntax support use replace instead of replaceAll (regex syntax support is only difference between these two methods). It is safer in case you would want to replace literals which can contain regex metacharacters like *, +, [, ] and others.
Read the documentation :) replaceAll() returns a new String, it does replace inside the existing String. The reason for that is that Strings are immutable objects.
The String object in Java is immutable. The replaceAll will not replace the data in the string, it will generate a new string. Try this:
query = query.replaceAll("REPLACEME", symbols.toString());
Related
This question already has answers here:
How do I split a string in Java?
(39 answers)
Split string with dot as delimiter
(13 answers)
Closed 2 years ago.
I have a string, which contains ^ symbol given below.
String tempName = "afds^afcu^e200f.pdf"
I want to split it like below
[afds, afcu, e200f]
How to resolve this.
The parameter to split() is a regular expression, which has special meta-characters. If the delimiter you're splitting on contains those special characters (e.g. ^), you have two options:
Escape the characters using \, which has to be doubled in a Java string literal to \\:
String[] result = tempName.split("\\^");
If you don't want to bother with that, or if the delimiter is dynamically assigned at runtime, so you can't escape the special characters yourself, call Pattern.quote() to do it for you:
String[] result = tempName.split(Pattern.quote("^"));
you need to add \\ in split method of String to split the string by this (^), because ^ is an special character in regular expression and you need to omit it with \\:
String tempName = "afds^afcu^e200f.pdf";
String [] result = tempName.split("\\^");
System.out.println(Arrays.toString(result));
Java characters that have to be escaped in regular expressions are:
.[]{}()<>*+-=!?^$|
Two of the closing brackets (] and }) are only need to be escaped after opening the same type of bracket.
In []-brackets some characters (like + and -) do sometimes work without escape.
more info...
String.split() in Java takes a regular expression. Since ^ is a control character in regex (when at the beginning of the regex string it means "the start of the line"), we need to escape it with a backslash. Since backslash is a control character in Java string literals, we also need to escape that with another backslash.
String tempName = "afds^afcu^e200f.pdf";
String[] parts = tempName.split("\\^");
You can use the retrieve a substring without the file extension and split that according to the delimiter that is required (^). This is shown below:
public static void main(String[] args) {
String tempName = "afds^afcu^e200f.pdf";
String withoutFileFormat = tempName.substring(0, tempName.length() - 4); //retrieve the string without the file format
String[] splitArray = withoutFileFormat.split("\\^"); //split it using the "^", use escape characters
System.out.println(Arrays.toString(splitArray)); //output the result
}
Required Output:
[afds, afcu, e200f]
This question already has answers here:
How to split a java string at backslash
(8 answers)
Closed 2 years ago.
In a apache camel processor methos I am trying to split a string, which was delivered from an Apache Kafka message broker as JSON. The split routine looks as follows:
String[] messageLines = new String[0];
if (messageBody.contains("\\n")) {
messageLines = messageBody.split("\\n");
} else {
messageLines = messageBody.split("\n");
}
In the debugger, the "messageBody" string looks like this:
"deviceName (string:1) -> TEST\nintValue (int:1) -> 123\ndoubleValue (double:1) -> 12.345\nacquisitionStamp (long:1) -> 1592468678231250944\nintArrayValue (int[]:10) -> [1,2,3,4,5,6,7,8,9,10]"
The code runs into the if (messageBody.contains("\\n")) {... part, but the .split("\\n") returns an array with one entry (the complete messageBody string) only. Same happens is I use .split("\n"). What is wrong here?
String.split() accepts a regex as argument. In order to match a literal backslash (\) in a string, you need 4 backslashes (\\\\) in your regex.
The backslash needs to be escaped once for the regex, and then the resulting two backslashes are escaped again for use in the string.
For your example, it would be:
messageLines = messageBody.split("\\\\n");
Please use StringTokenizer class to split(tokenise) the string instead of String.split().
StringTokenizer st = new StringTokenizer(str, "\n") to break the string in the new line.
or
StringTokenizer st = new StringTokenizer(str, "\\n") to break it when there is '\n'
This question already has answers here:
Java - String replace exact word
(6 answers)
Closed 3 years ago.
String str = "hdfCity1kdCity12fsd".
I want to replace only City1 with Goa without replacing City1 sequence in City1X in above String.
I tried using replace function.
str = str.replace("City1", "Goa")
but the result is
str = "hdfGoakdGoa2fsd"
how to do this selective replace? to get this desired result
str = "hdfGoakdCity12fsd";//solution: str.replaceAll("(?<!\\d)City1(?!\\d)", "Goa");
sorry for making my case not clear
Thanks #TiiJ7
In your case you could use replaceFirst(). This will only replace the first occurence of your matched String:
String str = "City1 is beautiful than City12";
str = str.replaceFirst("City1", "Goa");
System.out.println(str);
Will output:
Goa is beautiful than City12
Other than that you could use a more sophisticated regex to match your exact case, see for example this answer.
You can use replaceFirst() or replaceAll() method, but if you want to replace in the middle, you can find the occurrence you are looking for (one example here: Occurrences of substring in a string)
Use the index returned to make 2 substrings: the first part remain unchanged and, in the second part, the first occurrence must be replaced (replaceFirst())
Last: join the two substrings.
you can use the method replaceFirst(regex, replacement) :
String str = "City1 is beautiful than City12";
System.out.println(str.replaceFirst("City1", "Goa")); // Goa is beautiful than City12
If it's just about the first part, you could also use the substring method.
Example:
String str = "City1 is beautiful than City12";
str = "Goa" + str.substring(5);
If you're sure that City1 will not any characters around except whitespace you can use:
String str = "City1 is beautiful than than City12";
str = str.replace("City1 ", "Goa ");
System.out.println(str);
same as yours but additional space at the end of the replacing and new string
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Matching a “.” in java
I have a String 1.2.4 which i want to split and get 2 to compare it with another String that i get.
I am trying to do the following
StringTokenizer old_ver = new StringTokenizer(oldVersion, ".");
int oldVer = Integer.parseInt(old_ver.nextToken());
oldVer = Integer.parseInt(old_ver.nextToken());
StringTokenizer new_ver = new StringTokenizer(newVersion, ".");
int newVer = Integer.parseInt(new_ver.nextToken());
newVer = Integer.parseInt(new_ver.nextToken());
if (oldVer == newVer) {
return true;
}
IS there a better way to do it using .Split()
The problemis that in Regex "." is a single character. Hence, you need to escape it using "\\."
Similarly, you can use
string.split("\\.");
EDIT:
split() method of the String class uses Pattern and Matcher internally which is normally the API used for Regex in Java.
So there is no problem going with split.
In your code, 1.2.1 would be "compatible" with 3.2.0, and this looks like a serious problem, regardless if you use String.split or not. Also, you do not need to parse version numbers into integers as you only compare for equality.
StringTokenizer old_ver = new StringTokenizer(oldVersion, ".");
StringTokenizer new_ver = new StringTokenizer(newVersion, ".");
return (old_ver.nextToken().equals(new_ver.nextToken() &&
old_ver.nextToken().equals(new_ver.nextToken() );
You can surely do with String.split as well:
String [] oldV = String.split(oldVersion,"\\.");
String [] newV = String.split(newVersion,"\\.");
return oldV[0].equals(newV[0]) && oldV[1].equals(newV[1]);
The String.split() version seems slightly shorter but but for me it looks slightly more difficult to read because:
It involves additional thinking step that dot (.) is a reserved char and must be escaped.
"Next element and then following element" seems involving less thinking effort than "element at position 0 and then element at position 1".
It may pay to have some version comparator that first compares major, then intermediate and then minor parts of the version number the way that we could have the tests like "1.2.4 or later".
I am trying to replace a + character into a hyphen I have in my string.
String str = "word+word";
str.replaceAll('+ ', '-');
I tried using replace but it throwing an exception.Is there any other method to do this.
Use
str = str.replaceAll("\\+", "-");
A few errors in your code :
replaceAll takes strings, not chars
the + char must be escaped as the first argument is a regular expression (and \ itself must be escaped in java string literals)
you must take the return of the function : as String is immutable the function doesn't change it but returns another string
Just use replace:
str = str.replace('+', '-');
This one doesn't work on regex but take characters as they are.
Also as you see you have to reassing value again to your str variable because String in Java are immutable. In this case method replace doesn't change current String (str) but create new one with replaced + to '-'.
`replaceAll´ is for regular expressions and strings are immutable. Use:
str = str.replace("+", "-");
instead...
The replaceAll function takes a regular expression as its first argument. It so happens that + is a special character in regular expression language. Try replacing + with \\+. This will escape the plus sign, thus making the code to treat it like a normal character.
Also, the replaceAll method yields a string, so that will not work. Try doing:
String str = "word+word";
str = str.replaceAll("\\+ ", "-");
Use "" as opposed to '' in replaceAll.
String java.lang.String.replaceAll(String regex, String replacement)
If you are not sure about the escape sequence you need to use,
You could simply do this.
str = str.replaceAll(Pattern.quote("+"), "-");
This will automatically escape the regex predefined tokens to match in a literal way