Remove plaintext \n from string in Java - java

I am using the wikimedia api to get content from wikipedia pages. The api returns a lot of "\n" as plain text. I want to remove them from a string
s = s.replaceAll("\\n", "");
s = s.replaceAll("\n", "");
Neither of these work, any ideas?

When your String contains a plaintext \n it is actually a \\n otherwise it would be displayed as a linebreak, which is why I found s = s.replaceAll("\\\\n","") to be working for me. An example snippet:
class Main{
public static void main(String[] args){
String s = "Hello\\nHello";
System.out.println(s);
s = s.replaceAll("\\\\n","");
System.out.println(s);
}
}
Remember that replaceAll takes a Regex: Since you want to replace 2 /s you have to escape both of them, therefore////

Hi Please to use below code format:
s= s.replace("\n", "").replace("\r", "");
Thanks

You can use the code below:
s = s.replace("\n", "");
but, the newline character can be different among the environments.
So, you can use this
s = s.replace(System.getProperty("line.separator"), "");

Related

Removing some patterns before a particular string using Java

I want to remove some patterns between two "/" from the string, for example:
Input
/DT_Gateway/gateway/ACC/input/..
Output
/DT_Gateway/gateway/ACC
I have tried writing this code, but getting an error. I am new to Java, please help.
public class cut {
public static void main(String[] args) {
String myString = "/DT_Gateway/gateway/ACC/input/..";
String newString = myString.substring(myString.lastIndexOf("/")+1, myString.indexOf("/.."));
System.out.println(newString);
}
}
Note : this is a very custom solution to your problem, not a general way to do it .
String myString = "/DT_Gateway/gateway/ACC/input/..";
String newString = myString.substring(0, myString.indexOf("/i"));
System.out.println(newString);
Try this solution with regex:
"/DT_Gateway/gateway/ACC/input/..".replaceAll("(/[^/]+){2}$", "")
The regex is basically find two of the following pattern at the end of the string
/[^/]+
This means a forward slash followed by an unlimited number of non-forward-slashes.
It seems that relative paths should be normalized, XXX/.. removed.
That would go as follows
String myString = "/DT_Gateway/gateway/ACC/input/..";
System.out.println(myString.replaceAll("/[^/]+/\\.\\.(/|$)", "$1"));
String myString2 = "/DT_Gateway/gateway/ACC/input/../x.txt";
System.out.println(myString2.replaceAll("/[^/]+/\\.\\.(/|$)", "$1"));
Path path = Paths.get(myString);
System.out.println(path.normalize().toString());
Path path2 = Paths.get(myString2);
System.out.println(path2.normalize().toString());
/DT_Gateway/gateway/ACC
/DT_Gateway/gateway/ACC/x.txt
/DT_Gateway/gateway/ACC
/DT_Gateway/gateway/ACC/x.txt
Java Path is - for (all kinds of) file systems - quite the tool.
Especially as there is XXX/../..

Java String TRIM function not working

I am receiving a string from server trailing one or two lines of spaces like below given string.
String str = "abc*******
********";
Consider * as spaces after my string
i have tried a few methods like
str = str.trim();
str = str.replace(String.valueOf((char) 160), " ").trim();
str = str.replaceAll("\u00A0", "");
but none is working.
Why i am not able to remove the space?
You should try like this:
str = str.replaceAll("\n", "").trim();
You can observe there is a new line in that string . first replace new line "\n" with space("") and than trim
You should do:
str = str.replaceAll("\n", "");
In my case use to work the function trim()
Try this:
str = str.replaceAll("[.]*[\\s\t]+$", "");
I have tried your 3 methods, and them all work. I think your question describing not correctly or complete, in fact, a String in java would not like
String str = "abc*******
********";
They must like
String str = "abc*******"
+ "********";
So I think you should describe your question better to get help.

How to remove a substring in java

I am receiving a file path with "xyz" appended to it. name would look like D:/sdcard/filename.docxyz
i am using the below code to remove xyz but it is not working. what is missing here ?
String fileExtension = path.substring(path.lastIndexOf(".")+1);
String newExtension= fileExtension;
newExtension.replace("xyz", "");
path.replace(fileExtension, newExtension);
return path;
What is missing is that you need to save the result of your operations. Strings are immutable in Java, and the results of all String manipulations are therefore returned in the form of a new String:
newExtension = newExtension.replace("xyz", "");
path = path.replace(fileExtension, newExtension);
String in java are immutable, and changes upon it never occurs in place, but every time a new string is returned,
newExtension = newExtension.replace("xyz", "");
You could also use replaceAll() with a regex.
public static void main(String[] args) {
String s = "D:/sdcard/filename.docxyz";
System.out.println(s.replaceAll("xyz$", "")); // $ checks only the end
}
O/P :
input : s = "D:/sdcard/filename.docxyz";
D:/sdcard/filename.doc
input : String s = "D:/sdcard/filenamexyz.docxyz";
output : D:/sdcard/filenamexyz.doc
newExtension.replace("xyz", "");
Will only return string which has "xyz" removed but newExtension will remain as it is. Simple fix for your problem is use as below
String newExtension= fileExtension.replace("xyz", "");

Using regular expressions to rename a string

In java, I want to rename a String so it always ends with ".mp4"
Suppose we have an encoded link, looking as follows:
String link = www.somehost.com/linkthatIneed.mp4?e=13974etc...
So, how do I rename the link String so it always ends with ".mp4"?
link = www.somehost.com/linkthatIneed.mp4 <--- that's what I need the final String to be.
Just get the string until the .mp4 part using the following regex:
^(.*\.mp4)
and the first captured group is what you want.
Demo: http://regex101.com/r/zQ6tO5
Another way to do this would be to split the string with ".mp4" as a split char and then add it again :)
Something like :
String splitChar = ".mp4";
String link = "www.somehost.com/linkthatIneed.mp4?e=13974etcrezkhjk"
String finalStr = link.split(splitChar)[0] + splitChar;
easy to do ^^
PS: I prefer to pass by regex but it ask for more knowledge about regex ^^
Well you can also do this:
Match the string with the below regex
\?.*
and replace it with empty string.
Demo: http://regex101.com/r/iV1cZ8
Try below code,
private String trimStringAfterOccurance(String link, String occuranceString) {
Integer occuranceIndex = link.indexOf(occuranceString);
String trimmedString = (String) link.subSequence(0, occuranceIndex + occuranceString.length() );
System.out.println(trimmedString);
return trimmedString;
}

Java RegEx replace all characters in string except for a word

I am using the code in Java:
String word = "hithere";
String str = "123hithere12345hi";
output(str.replaceAll("(?!"+word+")", "x"));
However, rather than outputting: xxxhitherexxxxxxx like I want it to, it outputs: x1x2x3hxixtxhxexrxex1x2x3x4x5xhxix x, I've tried a load of different regex patterns to try to do this, but I can't seem to figure out how to do this :(
Any help would be much appreciated.
Well this technically works. Using only replace all and only one line, and it's assuming you string does not contain a deprecated ASCII character (BEL)
String string = "hithere";
String string2 = "asdfasdfasdfasdfhithereasasdf";
System.out.println(string2.replaceAll(string,"" + (char)string.length()).replaceAll("[^" + (char)string.length() + "]", "x").replaceAll("" + (char)string.length(), string));
I think this is what you're looking for, if I'm not mistaken:
String pattern = "(\\d)|(hi$)";
System.out.println("123hithere12345hi".replaceAll(pattern, "X"));
The pattern replaces any numeric digits and the word "hi".
This lookaround based code will work for you:
String word = "hithere";
String string = "123hithere12345hi";
System.out.println(string.replaceAll(
".(?=.*?\\Q" + word + "\\E)|(?<=\\Q" + word + "\\E(.){0,99}).", "x"));
//=> xxxhitherexxxxxxx

Categories

Resources