i have a space before a new line in a string and cant remove it (in java).
I have tried the following but nothing works:
strToFix = strToFix.trim();
strToFix = strToFix.replace(" \n", "");
strToFix = strToFix.replaceAll("\\s\\n", "");
myString.replaceAll("[ \t]+(\r\n?|\n)", "$1");
replaceAll takes a regular expression as an argument. The [ \t] matches one or more spaces or tabs. The (\r\n?|\n) matches a newline and puts the result in $1.
try this:
strToFix = strToFix.replaceAll(" \\n", "\n");
'\' is a special character in regex, you need to escape it use '\'.
I believe with this one you should try this instead:
strToFix = strToFix.replace(" \\n", "\n");
Edit:
I forgot the escape in my original answer. James.Xu in his answer reminded me.
Are you sure?
String s1 = "hi ";
System.out.println("|" + s1.trim() + "|");
String s2 = "hi \n";
System.out.println("|" + s2.trim() + "|");
prints
|hi|
|hi|
are you sure it is a space what you're trying to remove? You should print string bytes and see if the first byte's value is actually a 32 (decimal) or 20 (hexadecimal).
trim() seems to do what your asking on my system. Here's the code I used, maybe you want to try it on your system:
public class so5488527 {
public static void main(String [] args)
{
String testString1 = "abc \n";
String testString2 = "def \n";
String testString3 = "ghi \n";
String testString4 = "jkl \n";
testString3 = testString3.trim();
System.out.println(testString1);
System.out.println(testString2.trim());
System.out.println(testString3);
System.out.println(testString4.trim());
}
}
Related
In java 1.8.0
I am trying to replace %, but it is not matching
String str = "%28Sample text%29";
str.replaceAll("%29", "\\)");
str.replaceAll("%28", "\\(");
System.out.println("Replaced string is " + str);
I have tried all this Replace symbol "%" with word "Percent" Nothing worked for me. Thanks in Advance.
It's working.
You need re-assign to str
str = str.replaceAll("%29", "\\)");
str = str.replaceAll("%28", "\\(");
Jerry06's answer is correct.
But you could do this simply by using URLDecoder to decode those unicode value.
String s = "%28Hello World!%29";
s = URLDecoder.decode(s, "UTF-8");
System.out.println(s);
Will output :
(Hello World!)
The problem is that you misunderstood the usage of replaceall. It's for regex based replacements. What you need to use is the normal replace method like that:
String str = "%28Sample text%29";
str=str.replace("%29", "\\)"). replace("%28", "\\(");
System.out.println("Replaced string is " + str);
I have Strings "a,b,c,d,,,,, ", ",,,,a,,,,"
I want these strings to be converted into "a,b,c,d" and ",,,,a" respectively.
I am writing a regular expression for this. My java code looks like this
public class TestRegx{
public static void main(String[] arg){
String text = ",,,a,,,";
System.out.println("Before " +text);
text = text.replaceAll("[^a-zA-Z0-9]","");
System.out.println("After " +text);
}}
But this is removing all the commas here.
How can write this to achieve as given above?
Use :
text.replaceAll(",*$", "")
As mentioned by #Jonny in comments, can also use:-
text.replaceAll(",+$", "")
Your first example had a space at the end, so it needs to match [, ]. When using the same regular expression multiple times, it's better to compile it up front, and it only needs to replace once, and only if at least one character will be removed (+).
Simple version:
text = text.replaceFirst("[, ]+$", "");
Full code to test both inputs:
String[] texts = { "a,b,c,d,,,,, ", ",,,,a,,,," };
Pattern p = Pattern.compile("[, ]+$");
for (String text : texts) {
String text2 = p.matcher(text).replaceFirst("");
System.out.println("Before \"" + text + "\"");
System.out.println("After \"" + text2 + "\"");
}
Output
Before "a,b,c,d,,,,, "
After "a,b,c,d"
Before ",,,,a,,,,"
After ",,,,a"
Example:
Input
Str = P.O.Box
Output
Str= PO BOX
I can able to convert the string to uppercase and replace all dot(.) with a space.
public static void main(String args[]){
String s = "P.O.Box 1836";
String uppercase = s.toUpperCase();
System.out.println("uppercase "+uppercase);
String replace = uppercase.replace("."," ");
System.out.println("replace "+replace);
}
System.out.print(s.toUpperCase().replaceFirst("[.]", "").replaceAll("[.]"," "));
If you look the String API carefully, you would notice that there's a methods that goes by:-
replaceFirst(String regex, String replacement)
Hope it helps.
You have to use the replaceFirst method twice. First for replacing the . with <nothing>. Second for replacing the second . with a <space>.
String str = "P.O.Box";
str = str.replaceFirst("[.]", "");
System.out.println(str.replaceFirst("[.]", " "));
This one liner should do the job:
String s = "P.O.Box";
String replace = s.toUpperCase().replaceAll("\\.(?=[^.]*\\.)", "").replace('.', ' ');
//=> PO BOX
String resultValue = "";
String[] result = uppercase.split("[.]");
for (String value : result)
{
if (value.toCharArray().length > 1)
{
resultValue = resultValue + " " + value;
}
else
{
resultValue = resultValue + value;
}
}
Try this
System.out.println("P.O.Box".toUpperCase().replaceFirst("\\.","").replaceAll("\\."," "));
Out put
PO BOX
NOTE: \\ is needed here if you just use . only your out put will blank.
Live demo.
You should use replaceFirst method twice.
String replace = uppercase.replace("\\.", "").replaceFirst("\\.", "");
As you want to remove the first dot and replace the second one with a space, you need replace the whole P.O. section
Use
replace("P\\.O\\.", "PO ");
I am having a string which contains xyaahhfhajfahj{adhadh}fsfhgs{sfsf}.
Now I want to replace {string} with a space.
I want to replace the curly brackets and the string in it with null.
I want to use replaceFirst for it but I don't know the regex for doing it.
Try this:
public class TestCls {
public static void main(String[] args) {
String str = "xyaahhfhajfahj{adhadh}fsfhgs{sfsf}";
String str1 = str.replaceAll("\\{[a-zA-z0-9]*\\}", " ");// to replace string within "{" & "}" with " ".
String str2 = str.replaceFirst("\\{[a-zA-z0-9]*\\}", " ");// to replace first string within "{" & "}" with " ".
System.out.println(str1);
System.out.println(str2);
}
}
If you're saying that you want to find the first occurrence of anything inside of { and }, then replace it including the brackets with nothing, here's an example that will do that:
String input = "xyaahhfhajfahj{adhadh}fsfhgs{sfsf}";
String output = input.replaceFirst("\\{.*?\\}", "");
System.out.println(output ); // output will be "xyaahhfhajfahjfsfhgs{sfsf}"
I have a java string with " " from a text file the program accesses with a Buffered Reader object. I have tried string.replaceAll(" ","") and it doesn't seem to work.
Any ideas?
cleaned = cleaned.replace(" "," ");
cleaned = cleaned.replace("\u00a0","")
This is a two step process:
strLineApp = strLineApp.replaceAll("&"+"nbsp;", " ");
strLineApp = strLineApp.replaceAll(String.valueOf((char) 160), " ");
This worked for me. Hope it helps you too!
The same way you mentioned:
String cleaned = s.replace(" "," ");
It works for me.
There's a ready solution to unescape HTML from Apache commons:
StringEscapeUtils.unescapeHtml("")
You can also escape HTML if you want:
StringEscapeUtils.escapeHtml("")
Strings are immutable so You need to do
string = string.replaceAll(" ","")
You can use JSoup library:
String date = doc.body().getElementsByClass("Datum").html().toString().replaceAll(" ","").trim();
String.replace(char, char) takes char inputs (or CharSequence inputs)
String.replaceAll(String, String) takes String inputs and matches by regular expression.
For example:
String origStr = "bat";
String newStr = str.replace('a', 'i');
// Now:
// origStr = "bat"
// newStr = "bit"
The key point is that the return value contains the new edited String. The original String variable that invokes replace()/replaceAll() doesn't have its contents changed.
For example:
String origStr = "how are you?";
String newStr = origStr.replaceAll(" "," ");
String anotherStr = origStr.replaceAll(" ","");
// origStr = "how are you?"
// newStr = "how are you?"
// anotherStr = howareyou?"
We can have a regular expression check and replace HTML nbsp;
input.replaceAll("[\\s\\u00A0]+$", "") + "");
It removes non breaking spaces in the input string.
My solution is the following, and only this worked for me:
String string = stringWithNbsp.replaceAll("NNBSP", "");
Strings in Java are immutable. You have to do:
String newStr = cleaned.replaceAll(" ", "");
I encountered the same problem: The inner HTML of the element I needed had " " and my assertion failed.
Since the question has not accepted any answer,yet I would suggest the following, which worked for me
String string = stringwithNbsp.replaceAll("\n", "");
P.S : Happy testing :)