I'm writing code that's supposed to remove actual line breaks from a block of text and replace them with the String "\n". Then, when the String is read at another time, it should replace the line breaks (in other words, search for all "\n" and insert \n. However, while the first conversion works fine, it's not doing the latter. It seems as though the second replace is doing nothing. Why?
The replace:
theString.replaceAll(Constants.LINE_BREAK, Constants.LINE_BREAK_DB_REPLACEMENT);
The re-replace:
theString.replaceAll(Constants.LINE_BREAK_DB_REPLACEMENT, Constants.LINE_BREAK);
The constants:
public static final String LINE_BREAK = "\n";
public static final String LINE_BREAK_DB_REPLACEMENT = "\\\\n";
In String.replaceAll(regex, replacement), both the regex string and replacement string treat backslash as an escape character:
regex represents a regular expression, which escapes a backslash as \\
replacement is a replacement string, which also escapes backslashes:
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; see Matcher.replaceAll.
This means backslashes must be escaped in both parameters. Further, string constants also use backslash as an escape character, so backslashes in string constants passed to the method must be double-escaped (see also this question).
This works fine for me:
// Replace newline with "\n"
theString.replaceAll("\\n", "\\\\n");
// Replace "\n" with newline
theString.replaceAll("\\\\n","\n");
You can also use the Matcher.quoteReplacement() method to treat the replacement string as a literal:
// Replace newline with "\n"
theString.replaceAll("\\n", Matcher.quoteReplacement("\\n"));
// Replace "\n" with newline
theString.replaceAll("\\\\n",Matcher.quoteReplacement("\n"));
You dont need four backslashes in the last replaceAll() method call.
This seems to work fine for me
String str = "abc\nefg\nhijklm";
String newStr = str.replaceAll("\n", "\\\\n");
String newnewStr = newStr.replaceAll("\\\\n", "\n");
The output is:
abc
efg
hijklm
abc\nefg\nhijklm
abc
efg
hijklm
Which I think is what you expected.
Related
So for my app in Android Studio I want to replace the following:
String card = cards.get(count).getCard();
if (card.contains("{Player1}")) {
String replacedCard = card.replaceAll("{Player1}", "Poep");
}
An example of String card can be: {Player1} switch drinks with the person next to you.
Somehow I can't use {} for the replacing. With the { it says: "Dangling metacharacter". Screenshot: https://prnt.sc/s2bbl8
Is there a solution for this?
the first Argument of replaceAll is a String that is parsed to a regalar Expression (regEx). The braces { } are special reserved meta characters to express something within the regular expression. To match them as normal characters, you need to escape them with a leading backslash \ and because the backslash is also a special character you need to escape itself with an additional backslash:
String replacedCard = card.replaceAll("\\{Player1\\}", "Poep");
Both { } are reserved regex characters. Since the replaceAll() function takes in a regex parameter, you have to explicitly state that { and } are part of your actual string. You can do this by prefixing them with the escape character: \. But because the escape character is also a reserved character, you need to escape it too.
Here's the correct way to write your code:
String card = cards.get(count).getCard();
if (card.contains("{Player1}")) {
String replacedCard = card.replaceAll("\\{Player1\\}", "Poep");
}
You need to escape the initial { with \. I.e;
String card = "{Player1}";
if (card.contains("{Player1}")) {
String replacedCard = card.replaceAll("\\{Player1}", "Poep");
System.out.println("replace: " + replacedCard);
}
The method String.replaceAll expects a regular expression. The other answers already give a solution for this. However, if you don't need regular expressions, then you can also use String.replace:
String replacedCard = card.replace("{Player1}", "Poep");
Since the input value of the replaceAll method expects a regex, you need to escape the curly brackets with a backslash. The curly brackets are special characters in the context of regular expressions.
In Java a backslash in a regex is accomplished by a double backslash \\ (see https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html for reference).
So you would need to adjust the line like so:
String replacedCard = card.replaceAll("\\{Player1\\}", "Poep");
{} are special characters for Regular Expressions. replaceAll method takes as first parameter a Regular Expressions, so if you want also to replace the curly brackets you have to skip them with \\ , as follow:
String card = cards.get(count).getCard();
if (card.contains("{Player1}")) {
String replacedCard = card.replaceAll("\\{Player1}", "Poep");
}
I have a string with \r\n, \r, \n or \" characters in it. How can I replace them faster?
What I already have is:
String s = "Kerner\\r\\n kyky\\r hihi\\n \\\"";
System.out.println(s.replace("\\r\\n", "\n").replace("\\r", "").replace("\\n", "").replace("\\", ""));
But my code does not look beautiful enough.
I found on the Internet something like:
replace("\\r\\n|\\r|\\n|\\", "")
I tried that, but it didn't work.
You can wrap it in a method, put /r/n, /n and /r in a list. iterate the list and replace all such characters and return the modified string.
public String replaceMultipleSubstrings(String original, List<String> mylist){
String tmp = original;
for(String str: mylist){
tmp = tmp.replace(str, "");
}
return tmp;
}
Test:
mylist.add("\\r");
mylist.add("\\r\\n");
mylist.add("\\n");
mylist.add("\\"); // add back slash
System.out.println("original:" + s);
String x = new Main().replaceMultipleSubstrings(s, mylist);
System.out.println("modified:" + x);
Output:
original:Kerner\r\n kyky\r hihi\n \"
modified:Kerner kyky hihi "
I don't know if your current replacement logic be correct, but it says now that either \n, \r, or \r\n gets replaced with empty string, and backslash also gets replaced with empty string. If so, then you can try the following regex replace all:
String s = "Kerner\\r\\n kyky\\r hihi\\n \\\"";
System.out.println(s.replaceAll("\\r|\\n|\\r\\n|\\\\", ""));
One problem I saw with your attempt is that you are calling replace(), not replaceAll(), so it would only do a single replacement and then stop.
String.replaceAll() can be used, in your question you tried to use String.replace() which does not interpret regular expressions, only plain replacement strings...
You also need to escape the \\ again, i.e. \\\\ instead of \\
String s = "Kerner\\r\\n kyky\\r hihi\\n \\\"";
System.out.println(s.replaceAll("\\\\r|\\\\n|\\\\\"", ""));
Output
Kerner kyky hihi
Note the differences between String.replaceAll() and String.replace()
String.replaceAll()
Replaces each substring of this string that matches the given regular
expression with the given replacement.
String.replace()
Replaces each substring of this string that matches the literal target
sequence with the specified literal replacement sequence.
Use a regular expression if you want to do all the replaces in one go.
http://www.javamex.com/tutorials/regular_expressions/search_replace.shtml
I'm trying to replace some text in a file and the string contains a file path which requires some back slashes, normally using "\" works fine and produces a single \ on the output but my current code is not outputting any backslashes
String newConfig = readOld().replaceAll(readOld(),"[HKEY_CURRENT_USER\\Software\\xxxx\\xxxx\\Config]");
The "\" starts an escape sequence,
A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler.
So, (ludicrously perhaps)
String old = readOld();
String newConfig = old.replaceAll(old,
"[HKEY_CURRENT_USER\\\\Software\\\\xxxx\\\\xxxx\\\\Config]");
Or,
String old = readOld();
char backSlash = '\\';
String newConfig = old.replaceAll(old,
"[HKEY_CURRENT_USER" + backSlash + backSlash + "Software"
+ backSlash + backSlash + "xxxx"
+ backSlash + backSlash + "xxxx"
+ backSlash + backSlash + "Config]");
You should use replace here as it may possible your readOld() method may be having some special characters (i.e +,*,. etc.) which are reserved in regExp so better to use replace.(As replaceAll may throw Exception for invalid regular Expression)
String newConfig = readOld().replace(readOld(),"replacement");
As here it seems you are replacing whole String why not just assign String directly to newConfig
From JavaDoc for replaceAll
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
So either go For \\\\ (As suggested by Elliott Frinch) in String or use replace.
The Below java code replaces all the character in string variable BusDetails with blank even though i don't see a (. dot) for the method to replace it. Why ?
Output = _BusDetails
String BusDetails = " BUS_12_UFV_BOURQUIN_COMMUTER_TO_UFV";
String table_UniqueBusNameTimings = BusDetails.replaceAll(".", "")+"_BusTimings";
System.out.println("TableName: "+table_UniqueBusNameDetails);
replaceAll treats its first argument as a regular expression, and in regular expressions a dot matches any single character except a newline.
To replace one fixed string with another you should use the replace method that takes two CharSequence parameters instead - despite its name, this method does in fact replace all occurrences of the first CharSequence with the second one.
String table_UniqueBusNameTimings = BusDetails.replace(".", "")+"_BusTimings";
You need to escape that meta character
String table_UniqueBusNameTimings = BusDetails.replaceAll("\\.", "")+"_BusTimings";
See how escapes works in java
http://docs.oracle.com/javase/jndi/tutorial/beyond/names/syntax.html
you need to escape the period, like this:
String BusDetails = " BUS_12_UFV_BOURQUIN_COMMUTER_TO_UFV";
String table_UniqueBusNameTimings = BusDetails.replaceAll("\\.", "")+"_BusTimings";
System.out.println("TableName: "+table_UniqueBusNameTimings);
I want to remove all Unicode Characters and Escape Characters like (\n, \t) etc. In short I want just alphanumeric string.
For example :
\u2029My Actual String\u2029
\nMy Actual String\n
I want to fetch just 'My Actual String'. Is there any way to do so, either by using a built in string method or a Regular Expression ?
Try
String stg = "\u2029My Actual String\u2029 \nMy Actual String";
Pattern pat = Pattern.compile("(?!(\\\\(u|U)\\w{4}|\\s))(\\w)+");
Matcher mat = pat.matcher(stg);
String out = "";
while(mat.find()){
out+=mat.group()+" ";
}
System.out.println(out);
The regex matches all things except unicode and escape characters. The regex pictorially represented as:
Output:
My Actual String My Actual String
Try this:
anyString = anyString.replaceAll("\\\\u\\d{4}|\\\\.", "");
to remove escaped characters. If you also want to remove all other special characters use this one:
anyString = anyString.replaceAll("\\\\u\\d{4}|\\\\.|[^a-zA-Z0-9\\s]", "");
(I guess you want to keep the whitespaces, if not remove \\s from the one above)