How do I make multi replace() java - java

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

Related

Java code replaceall method replaces a string with blank value?

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

replaceAll not working for below query

After executing the below line the b contains the value "\%AMPAMP\$". I want it to be "&". Please help.
String b = a.replaceAll("\%AMPAMP\$", "&");
String is immutable. See the public String replaceAll(String regex,String replacement):
Returns:
The resulting String
You should do:
a = a.replaceAll("\%AMPAMP\$", "&");
Edit:
After you said that you did save it, you should now notice that replaceAll takes a regex and not a String. You should escape the special characters (Escaping a regex is done by \, but in Java \ is written as \\), or use String#quote:
a = a.replaceAll(Pattern.quote("\%AMPAMP\$"), "&");
You don't really need a regex here. Use String#replace(String search, String replace) method like this:
b = a.replace("%AMPAMP$", "&");
btw String#replaceAll method needs a regex where you need to use double backslash to escape $:
b = a.replaceAll("%AMPAMP\\$", "&");

Why does reinserting line breaks after removing them not work?

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.

How to remove a carriage return from a string

String s ="SSR/DANGEROUS GOODS AS PER ATTACHED SHIPPERS
/DECLARATION 1 PACKAGE
NFY
/ACME CONSOLIDATORS"
How to strip the space between "PACKAGE" and "NFY" ?
Java's String.replaceAll in fact takes a regular expression. You could remove all newlines with:
s = s.replaceAll("\\n", "");
s = s.replaceAll("\\r", "");
But this will remove all newlines.
Note the double \'s: so that the string that is passed to the regular expression parser is \n.
You can also do this, which is smarter:
s = s.replaceAll("\\s{2,}", " ");
This would remove all sequences of 2 or more whitespaces, replacing them with a single space. Since newlines are also whitespaces, it should do the trick for you.
Try this code:
s = s.replaceAll( "PACKAGE\\s*NFY", "PACKAGE NFY" );
s = s.replaceAll("[\\n\\r]", "");
Have you tried a replace function? Something in the lines of:
youString.Replace("\r", "")
string = string.replace(/\s{2,}/g, ' ');

How to Replace dot (.) in a string in Java

I have a String called persons.name
I want to replace the DOT . with /*/ i.e my output will be persons/*/name
I tried this code:
String a="\\*\\";
str=xpath.replaceAll("\\.", a);
I am getting StringIndexOutOfBoundsException.
How do I replace the dot?
You need two backslashes before the dot, one to escape the slash so it gets through, and the other to escape the dot so it becomes literal. Forward slashes and asterisk are treated literal.
str=xpath.replaceAll("\\.", "/*/"); //replaces a literal . with /*/
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)
If you want to replace a simple string and you don't need the abilities of regular expressions, you can just use replace, not replaceAll.
replace replaces each matching substring but does not interpret its argument as a regular expression.
str = xpath.replace(".", "/*/");
Use Apache Commons Lang:
String a= "\\*\\";
str = StringUtils.replace(xpath, ".", a);
or with standalone JDK:
String a = "\\*\\"; // or: String a = "/*/";
String replacement = Matcher.quoteReplacement(a);
String searchString = Pattern.quote(".");
String str = xpath.replaceAll(searchString, replacement);
return sentence.replaceAll("\s",".");

Categories