Java String Split Behavior - Split on Dollar Symbol [duplicate] - java

This question already has answers here:
Why can't I split a string with the dollar sign?
(6 answers)
Closed 7 years ago.
I am trying the following code (running java version 1.7 in Eclipse Luna IDE on Ubuntu Linux 12.04):
String str = "abc$xyz";
String[] split_ = str.split("$");
System.out.println(split_.length);
I am always getting a split of length 1. If I try to print split_[0], I am always getting the entire string. Can anyone suggest what might be the cause?

This is because split expects a regular expression. Since "$" is the end-of-line marker in a regular expression, this only splits on the end of the String.
You should use
String str = "abc$xyz";
String[] split_ = str.split("\\$");
System.out.println(split_.length);
instead.
This escapes the "$", so that it's treated as a literal character instead (and uses two slashes to escape the backslash as part of the string literal).

The $ character is a metacharacter meaning "end of line", not a literal dollar sign.
Escape the $ character with two backslashes, one to escape the $ in the regular expression, one for a Java escape for a backslash.
String[] split_ = str.split("\\$");

.split() uses regex that is why...
Try this:
String str = "abc$xyz";
String[] split_ = str.split("\\$");
System.out.println(split_.length);

Related

How to replace "\" with "/" in java? [duplicate]

This question already has answers here:
Java replaceAll: Cannot replace string with backslash
(3 answers)
What are all the escape characters?
(5 answers)
Closed 11 months ago.
I have a string like s = "abc\def" and I want to replace "" with "/" and makes the string like "abc/def/".
I tried replaceAll("\\","/") but the compiler is giving error for string
error: illegal escape character
String s="abc\def";
The issue is that Java uses \ as the string escape character, but also as the regex escape character, and replaceAll performs a regex search. So you need to doubly escape the backslash (once to make it a literal \ in the string, and once to make it a literal character in the regular expression):
result = str.replaceAll("\\\\", "/");
Alternatively, you don’t actually need regular expressions here, so the following works as well:
result = str.replace("\\", "/");
Or, indeed, using the single-char replacement version:
result = str.replace('\\', '/');

Using Regex for splitting a string in java [duplicate]

This question already has answers here:
Why does this Java regex cause "illegal escape character" errors?
(7 answers)
Closed 3 years ago.
I want to split a string in java with white spaces. I know that the below line of code does it.
String s[] = str.split("\\\s+");
Here split function takes the regex by which the string must be split. So when I want to split string str through one or more spaces, I should pass \s+ as regex, then why is \\\s+ used?
This will do the split
String s[] = n.split("\\s+");
You don't need a third slash'\' - you get Compile Error.
And first '\' is for escaping the second '\'. Used as an escape character for '\s'.
Like Ismail said, you don't need the third backslash.
In your regex you want to use \s so in Java you also need to escape your backslashes for your tags.
Solution:
Why does this Java regex cause "illegal escape character" errors?

How to split a java string with "("? [duplicate]

This question already has answers here:
Groovy/Java split string on parentheses "("
(5 answers)
What special characters must be escaped in regular expressions?
(13 answers)
Closed 3 years ago.
I am trying to split a java string with the character "(".
For example :
split("wer(sde")= "wer"+"sde".
But it give exception. Is there a way to split this string using split() function without changing the character "(" to some other character.
String[] cp=cmd.split("{");
Output:
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition
The thing is, split() receives as parameter a regular expression. Both {} and () are meta-characters and have a special meaning in a regex, so you need to escape them like this:
String[] cp = cmd.split("\\(|\\)");
The method split of String accept a String, that parameter is a regex :
public String[] split(String regex)
Splits this string around matches of the given regular expression.
Since ( is a reserved character in regex, you need to escape it \(.
But in Java, you need to escape twice \\(, once for the String and the second for the regex
This gives :
s.split("\\(");
Parentheses mean something in RegEx, they're used to group characters together. As such, if you intend to reference the literal character, '(' you must escape it within the RegEx:
String[] cp = cmd.split("\\(");
Note the use of two backslashes. This is because the JVM will also interpret a backslash as a metacharacter for escape purposes, so you must escape the backslash itself with another backslash in order for it to make it into the RegEx.

| not recognized in java string.split() method [duplicate]

This question already has answers here:
Splitting a Java String by the pipe symbol using split("|")
(7 answers)
Closed 8 years ago.
I am having problems with the java string.split method.
I have a string word like so, which equals- freshness|originality. I then split this string like so:
String words[] = word.split("|");
If I then output words[1], like so:
t1.setText(words[1]);
It gives me the value f. I have worked out that this is the f in the word freshness.
How can I split the string properly so that words[1] is actually originality? Thanks for the help!
You should escape it:
String words[] = word.split("\\|");
Check this explanation in similar question here: Why does String.split need pipe delimiter to be escaped?
String object's split() method has a regular expression as a parameter. That means an unescaped | is not interpreted as a character but as OR and means "empty string OR empty string".
You need to escape the pipe because java recognizes it as a Regular Expression OR Operator.
line.split("\\|")
"|" gets is parsed as "empty string or empty string," which isn't what you are trying to find.
For the record
... ? . + ^ : - $ *
are all Regex Operators and need to be escaped.
You need to escape the character. Use "\\|".
More information on regex escaped characters here.
String test ="freshness|originality";
String[] splits = test.split("\\|");
String part1 = splits[0]; // freshness
String part2 = splits[1]; // originality

split() function for '$' not working [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
What special characters must be escaped in regular expressions?
(13 answers)
Closed 8 years ago.
I'm doing a simple code
String splitString = "122$23$56$rt";
for(int i=0;i<splitString.split("$").length;i++){
System.out.println("I GOT IS :: "+splitString.split("$")[i]);
}
When I split like
splitString.split("$")
It is giving me output [122$23$56$rt]
Why this is not splinting on '$'?
String.split() takes in regex as argument and $ is a metacharacter in Java regex API. Therefore, you need to escape it:
String splitString = "122$23$56$rt";
for(int i=0;i<splitString.split("\\$").length;i++){
System.out.println("I GOT IS :: "+splitString.split("\\$")[i]);
}
Other metacharacters supported by the Java regex API are: <([{\^-=!|]})?*+.>
split(Pattern.quote("$"))
Is my favorite.
See Pattern#quote:
Returns a literal pattern String for the specified String.
Your code doesn't work because $ has a special meaning in regex, and since String#split takes a regex as an argument, the $ is not interpreted as the String "$", but as the special meta character $.
Escape it. the split() method takes a regex: split("\\$")
try something like this
String splitString = "122$23$56$rt";
for(int i=0;i<splitString.split("\\$").length;i++){
System.out.println("I GOT IS :: "+splitString.split("$")[i]);
}
NOTE: split() uses a regular expression.
Your regular expression uses a special character ie $
$ is the regular expression for "end of line".
String splitString = "122$23$56$rt";
for(int i=0;i<splitString.length;i++){
System.out.println("Now you GOT this :: "+split(Pattern.quote("$")));
}
There are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".
So your $ is also metacharacter as defination says so you can't split using simple function. Though you must use pattern in this case.
Thanks..
Escape it like
split("\\$")
instead of split("$")
It will not work because split() takes input as RegEx
String splitString = "122$23$56$rt";
for(int i=0;i<splitString.split("\\$").length;i++){
System.out.println("I GOT IS :: "+splitString.split("\\$")[i]);
}
String.split(), .match(), .replaceAll() are some of the methods that use RegEx pattern and so you should look at the javadoc of the Pattern class:
If your splitting character happen to be one of the pattern characters, you must escape it with \\, in this case your split call should be: .split("\\$")

Categories

Resources