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'
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:
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:
Java - How to split a string on plus signs?
(2 answers)
What special characters must be escaped in regular expressions?
(13 answers)
Closed 4 years ago.
Just found out, that I get a NullPointerException when trying to split a String around +, but if I split around - or anything else (and change the String as well of course), it works just fine.
String string = "Strg+Q";
String[] parts = string.split("+");
String part1 = parts[0]; //Strg
String part2 = parts[1]; //Q
Would love to hear from you guys, what I am doing wrong!
This one works:
String string = "Strg-Q";
String[] parts = string.split("-");
String part1 = parts[0]; //Strg
String part2 = parts[1]; //Q
As + is one of the special regex syntaxes you need to escape it.
Use
String[] parts = string.split("\\+");
Instead of
String[] parts = string.split("+");
Try this:
final String string = "Strg+Q";
final String[] parts = string.split("\\+");
System.out.println(parts[0]); // Strg
System.out.println(parts[1]); // Q
It happens because + is a special character in Regex - it's the match-one-or-more quantifier.
The only thing you need to do is to escape it:
String[] parts = string.split("\\+");
String.split(...) expects a Regular Expression and the '+' is a special character. Try:
String string = "Strg+Q";
String[] parts = string.split("[+]");
String part1 = parts[0]; //Strg
String part2 = parts[1]; //Q
+ is a special regex character which means that you need to escape it in order to use it as a normal character.
String[] parts = string.split("\\+");
The problem you got here is that "+" is a meta character in Java, so you need to "scape" it by using "\\+".
As others have mentioned, '+' is special when dealing with regex. In general, if a character is special you can use Pattern.quote() to escape it, as well as "\\+". Documentation on Pattern: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
Example:
String string = "Strg-Q";
String[] parts = string.split(Pattern.quote("+"));
String part1 = parts[0]; //Strg
String part2 = parts[1]; //Qenter code here
Remember to import pattern from java.util.regex!
Amit beat me too it. string.split() takes a regular expression as its argument. In regexes + is a special symbol. Escape it with a backslash. Then, since it's a java string, escape the backslash with another backslash, so you get \+. Try testing your regular expressions on an online regex tester.
This question already has an answer here:
Divide/split a string on quotation marks
(1 answer)
Closed 8 years ago.
This question is Pretty Simple
How to Split String With double quotes in java?,
For example I am having string Do this at "2014-09-16 05:40:00.0",After Splitting, I want String like
Do this at
2014-09-16 05:40:00.0,
Any help how to achieve this?
This way you can escape inner double quotes.
String str = "Do this at \"2014-09-16 05:40:00.0\"";
String []splitterString=str.split("\"");
for (String s : splitterString) {
System.out.println(s);
}
Output
Do this at
2014-09-16 05:40:00.0
Use method String.split()
It returns an array of String, splitted by the character you specified.
public static void main(String[] args) {
String test = "Do this at \"2014-09-16 05:40:00.0\"";
String parts[] = test.split("\"");
String part0 = parts[0];
String part1 = parts[1];
System.out.println(part0);
System.out.println(part1);
}
output
Do this at
2014-09-16 05:40:00.0
Try this code. Maybe it can help
String str = "\"2014-09-16 05:40:00.0\"";
String[] splitted = str.split("\"");
System.out.println(splitted[1]);
The solutions provided thus far simply split the string based on any occurrence of double-quotes in the string. I offer a more advanced regex-based solution that splits only on the first double-quote that precedes a string of characters contained in double quotes:
String[] splitStrings =
"Do this at \"2014-09-16 05:40:00.0\"".split("(?=\"[^\"].*\")");
After this call, split[0] contains "Do this at " and split[1] contains "\"2014-09-16 05:40:00.0\"". I know you don't want the quotes around the second string, but they're easy to remove using substring.
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());