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

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('\\', '/');

Related

In java I how do I escape a * character [duplicate]

This question already has answers here:
Java doesn't work with regex \s, says: invalid escape sequence
(3 answers)
Closed 3 years ago.
I have a string
String a = "dcvdk*vmfdkvm*bmkjfnb*";
I want to replace the * character by space
I tried a.replaceAll("\*", " ");
But it is giving error as invalid escape sequence.
Can you please tell me how can I achieve this?
Escape the escape character:
"\\*"
Alternatively, just use replace, which treats the arguments as literals, not regexes:
a.replace("*", " ")
Or, as Aniket Sahrawat points out, you can use the char overload in this case:
a.replace('*', ' ')
Remember that the backslash have a special meaning in strings, and you need to escape the backslash itself to get an actual backslash:
a.replaceAll("\\*", " ");

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.

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

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);

| 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

Java regex ignore '.' symbol [duplicate]

This question already has answers here:
Java RegEx meta character (.) and ordinary dot?
(9 answers)
Closed 9 years ago.
I'm trying to split a string at every '.' (period), but periods are a symbol used by java regexes. Example code,
String outstr = "Apis dubli hre. Agro duli demmos,".split(".");
I can't escape the period character, so how else do I get Java to ignore it?
Use "\\." instead. Just using . means 'any character'.
I can't escape the period character, so how else do I get Java to ignore it?
You can escape the period character, but you must first consider how the string is interpreted.
In a Java string (that is fed to Pattern.compile(s))...
"." is a regex meaning any character.
"\." is an illegally-escaped string. This won't compile. As a regex in a text editor, however, this is perfectly legitimate, and means a literal dot.
"\\." is a Java string that, once interpreted, becomes the regular expression \., which is again the escaped (literal) dot.
What you want is
String outstr = "Apis dubli hre. Agro duli demmos,".split("\\.");

Categories

Resources