Replace ' with \' in string using String.replaceAll() - java

Replace ' with \' using the String.replaceAll() is not working.
String t="It can't be done";
String title=t.replaceAll("'", "\\\'");
syso(title);
Expected output: It can\'t be done

You may need to double escape the slash.
t.replaceAll("'", "\\'")

Unusual output but you need one extra slash \:
t.replaceAll("'", "\\\\'")

Related

Replace dot in between slash i.e. '/./' with single slash '/'

For this string dirPath,
String dirPath = "c:/create/a/dir/very/deep/inside/../././../../../dir/";
I want the output string to look like :
"c:/create/a/dir/very/deep/inside/../../../../dir/";
I used :
dirPath.replaceAll("/[.]/", "/");
but that gave :
c:/create/a/dir/very/deep/inside/.././../../../dir/
^^^
then, tried with one more replaceAll as:
dirPath.replaceAll("/[.]/", "/").replaceAll("/[.]/", "/");
and that worked!
My question is why couldn't one call achieve the same result?
How to achieve it in simplest way?
P.S. Another regex that didn't work for me : .replaceAll("($|/)[.]/", "$1")
You can use a lookahead pattern to avoid consuming the slash needed by the subsequent match:
dirPath.replaceAll("/\\.(?=/)", "")
Demo: https://regex101.com/r/qWKVU3/1 or http://tpcg.io/ijmYJF

Regex escape sequence error in Java

p = "<a href=\".*?\"\\stitle=\"(.*?\")>.*?<\/a><span class=\"event-nodetype\">\((.*?\)</span><span class=\"event-timeleft\">\()(.*?\)<\/span><li>)";
This is regex i created for
YOK ED?LEN MEDEN?YET: GEÇ OSMANLI VE ERKEN CUMHUR?YET DÖNEMLER?NDE GAYR?MÜSL?M VARLI?I<span class="event-nodetype">(Konferans / Kongre / Sempozyum)</span><span class="event-timeleft">(Devam etmekte)</span><li>
But eclipse gives error of
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )
I put \ to " and other things but still i cant fix it.
What is the problem?
When i split the line into 4 lines
p = "<a href=\".*?\"\\stitle=\"(.*?\")>"
+ ".*?<\/a><span class=\"event-nodetype\">\(("
+ ".*?\)</span><span class=\"event-timeleft\">\()("
+ ".*?\)<\/span><li>)";
the error seems on line 2.
\" is correct, an so is \\s (but I would use \\s+). All the other backslashes in your regex need to be escaped: \\/, \\(, \\) (/ doesn't need escaping, but doing so doesn't hurt anything). This is for the string literal, not for the regex; the backslash is an escape character for both.

Representing carriage returns and quotes with regular expressions in java

I want to replace a carriage return followed by quotation marks with just quotation marks. For example, if I have:
Hello World
"Hello World"
I would like the result to be:
Hello World"Hello World"
This is my attempt, where String text is what I have above:
String adjusted = text.replaceAll("[\n][\"], "\"");
However, my IDE does not accept this.
Thanks for the help!
String adjusted = text.replaceAll("(?m)\r?\n\"", "\"");
The (?m) is for multi-line usage, for \r for a real CR in Windows (CR+LF).
You can use replace instead of replaceAll to avoid matching regular expression, but instead matching literals.
String adjusted = text.replace("\n\"", "\"");
If you want this method to use you operating system line separators you should use
String adjusted = text.replace(System.lineSeparator()+"\"", "\"");
You should do it in a platform agnostic way like:
String newline = System.getProperty("line.separator");
String newStr = str.replaceAll(newline, "\"");

replacing '\\' string with '\' in java

Hi we have a string like "ami\\303\\261o". we want to replace \\ with \.
We have tried the following:
replace("\\", "\")
replaceAll("\\", "\")
But we didn't get proper output.
For use in a Java regex, you need to escape the backslashes twice:
resultString = subjectString.replaceAll("\\\\\\\\", "\\\\");
In a regex, \\ means "a literal backslash".
In a Java string, "\\" encodes a single backslash.
So, a Java string that describes a regex that matches a single backslash is "\\\\"
And if you want to match two backslashes, it's "\\\\\\\\", accordingly.
You must keep backslash escaping in mind. Use
public class so {
public static void main(String[] args) {
String s = "ami\\\\303\\\\261o";
System.out.println(s);
s = s.replace("\\\\", "\\");
System.out.println(s);
}
};
Each backslash escapes the following backslash and resolves to the two literal strings \\ and \
Also keep in mind, String.replace returns the modified string and keeps the original string intact.
No need of regex here. Escape the slashes and use replace()
someString.replace('\\\\', '\\');
Thats because the \\ inside your input String get internally replaced by \ because of the Java Escape Character.
That means that if you output your String without performing any regex on it, it would look like this: "ami\303\261o".
Generally you should remember to escape every escape-character with itself:
\ -> escaped = \\
\\ -> escaped = \\\\
\\\ -> escaped = \\\\\\
...and so on
Try below code
String val = "ami\\303\\261o";
val =val.replaceAll("\\\\", "\\\\");
System.out.println(val);
Outpout would be
ami\303\261o
A Fiddle is created here check it out
Java Running Example

Why am I getting a StringIndexOutOfBoundsException when I try to replace `\\` with `\`?

I have to replace \\ with \ in Java. The code I am using is
System.out.println( (MyConstants.LOCATION_PATH + File.separator + myObject.getStLocation() ).replaceAll("\\\\", "\\") );
But I don't know why it is throwing StringIndexOutOfBoundsException.
It says String index out of range: 1
What could be the reason? I guess it is because the first argument replaceAll accepts a pattern. What could be the possible solution?
Stacktrace
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:558)
at java.util.regex.Matcher.appendReplacement(Matcher.java:696)
at java.util.regex.Matcher.replaceAll(Matcher.java:806)
at java.lang.String.replaceAll(String.java:2000)
Answer Found
asalamon74 posted the code I required, but I don't know why he deleted it. In any case here it is.
There is a bug already filed in Java's bug database. (Thanks for this reference, asalamon.)
yourString.replaceAll("\\\\", "\\\\");
Amazingly, both search and replace string are the same :) but still it does what I require.
Use String.replace instead of replaceAll to avoid it using a regex:
String original = MyConstants.LOCATION_PATH + File.seperator
+ myObject.getStLocation();
System.out.println(original.replace("\\\\", "\\"));
Personally I wouldn't do it this way though - I'd create MyConstants.LOCATION_PATH_FILE as a File and then you could write:
File location = new File(MyConstants.LOCATION_PATH_FILE,
myObject.getStLocation());
which will do the right thing automatically.
Well, i tried
String test = "just a \\ test with some \\\\ and others \\\\ or \\ so";
String result = test.replaceAll("\\\\", "\\\\");
System.out.println(test);
System.out.println(result);
System.out.println(test.equals(result));
and got, as expected
just a \ test with some \\ and others \\ or \ so
just a \ test with some \\ and others \\ or \ so
true
What you really need is
string.replaceAll("\\\\\\\\", "\\\\");
to get
just a \ test with some \\ and others \\ or \ so
just a \ test with some \ and others \ or \ so
false
You want to find: \\  (2 slashes)
which needs to be escaped in the regex: \\\\ (4 slashes)
and escaped in Java: "\\\\\\\\" (8 slashes)
same for the replacement...
For the regex, if you want to change \ to \\, you should do this:
if (str.indexOf('\\') > -1)
str = str.replaceAll("\\\\", "\\\\\\\\");
str = "\"" + str + "\"";
Where \\\\ means \ and \\\\\\\\ means \\.
File.seperator is already escaped as is any string object so you are escaping them twice.
You only need to escape values that you are entering as a string literal.
The best way is :
str.replace(**'**\\**'**, **'**/**'**); //with char method not String
Try this
cadena.replaceAll("\\\\","\\\\\\\\")
I suspect the problem is that replaceAll() uses regexps and the backslash is an escape character in regexps as well as in Java - it might be necessary to double the number of backslashes.
In general you should always post the full stack trace of exceptions, it is much easier to diagnose the problem that way.
I believe what you need to do is:
System.out.println( (MyConstants.LOCATION_PATH + File.separator + myObject.getStLocation() ).replaceAll("\\\\\\\\", "\\\\") );
The regular expression String is actually four backslashes, which is a regular expression that matches two backslashes.
The replacement String has to be four slashes as per Java documentation, from:
http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#replaceAll(java.lang.String)
Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.
final StringBuilder result = new StringBuilder();
final StringCharacterIterator iterator = new StringCharacterIterator(str);
char character = iterator.current();
while (character != CharacterIterator.DONE )
{
if (character == '\\\\') {
result.append("\\");
}
else {
result.append(character);
}
character = iterator.next();
}
System.out.print(result);

Categories

Resources