I am trying to add a line break in blueJ but it won't work since the return type of String will return the literal character. I have tried both \r\n and \n same result.
public String testNl(){
String str1 = "1st Line";
String str2 = "text 2nd";
String linebreak = str1 + "\n" + str2;
return linebreak;
}
Result: 1st Line\ntext 2nd
Related
How to replace space and \r in string with delimiter value?
String oldDelimiter = " ";
String newDelimiter = "o";
String fileContent = "try some **random** %!(chars)!% ##\r" +
"or line break$# \r" +
":(";
fileContent = fileContent.replaceAll("[" + oldDelimiter + "]+", newDelimiter);
fileContent = fileContent.replaceAll("\r", newDelimiter);
current output: tryosomeo**random**o%!(chars)!%o##oorolineobreak$#oo:(
desired output: tryosomeo**random**o%!(chars)!%o##oorolineobreak$#o:(
Notice the extra letter o towards the end of the string after the # symbol.
Update: it should only replace with o if there is a space or \r. However, if both space and \r and next to each other, then only replace with one o delimiter.
Like Andreas said, use the "[ \r]" to replace all of the \r and " " with spaces.
fileContent = fileContent.replaceAll("[ \r]+", "o");
How can I use java string replaceAll or replaceFirst to append to beginning?
String joe = "Joe";
String helloJoe = joe.replaceAll("\\^", "Hello");
Desired Output: "Hello Joe"
You don't need to escape ^ because ^ is a special meta character in regex which matches the start of a line.
String helloJoe = whatever.replaceFirst("^", "Hello ");
You could perform a simple String append with +, or String.format(String, Object...) like
String whatever = "Joe";
String helloJoe = String.format("Hello %s", whatever);
// String helloJoe = "Hello " + whatever;
System.out.println(helloJoe);
Output is (as requested)
Hello Joe
How to remove multiple spaces and newlines in a string, but preserve at least one blank line for each group of blank lines.
For example, change:
"This is
a string.
Something."
to
"This is
a string.
Something."
I'm using .trim() to strip whitespace from the beginning and end of a string, but I couldn't find anything for removing multiple spaces and newlines in a string.
I would like to keep just one whitespace and one newline.
The one-line solution to remove multiple spaces/newlines, but preserve at least one blank line from multiple blank lines:
str = str.replaceAll("(?m)(^ *| +(?= |$))", "").replaceAll("(?m)^$([\r\n]+?)(^$[\r\n]+?^)+", "$1");
Each individual line is trimmed too.
Here's some test code:
String str = " This is\r\n " +
"\r\n" +
" \r\n " +
" \r \n \n " +
"\r\n" +
" a string. ";
str = str.trim().replaceAll("(?m)(^ *| +(?= |$))", "").replaceAll("(?m)^$([\r\n]+?)(^$[\r\n]+?^)+", "$1");
System.out.println(str);
Output:
This is
a string.
The previous advice will trim all whitespace, including the linefeeds and replace them with a single space.
text.replaceAll("\\n\\s*\\n", "\\n").replaceAll("[ \\t\\x0B\\f]+", " ").trim());
First it replaces any instances of linefeeds with only whitespace between them with a single linefeed, then it trims down any other whitespace to a single space ignoring linefeeds.
Here is what I came up with after a bit of testing...
public String keepOneWS(String str) {
Pattern p = Pattern.compile("(\\s+)");
Matcher m = p.matcher(str);
Pattern pBlank = Pattern.compile("[ \t]+");
String newLineReplacement = System.getProperty("line.separator") +
System.getProperty("line.separator");
StringBuffer sb = new StringBuffer();
while (m.find()) {
if(pBlank.matcher(m.group(1)).matches()) {
m.appendReplacement(sb, " ");
} else {
m.appendReplacement(sb, newLineReplacement);
}
}
m.appendTail(sb);
return sb.toString().trim();
}
public void testKeepOneWS() {
String str = " This \t is\r\n " +
"\r\n" +
" \r\n " +
" \r \n \t \n " +
"\r\n" +
" a \t string. \t ";
String expected = "This is" + System.getProperty("line.separator")+
System.getProperty("line.separator") + "a string.";
String actual = keepOneWS(str);
System.out.println("'" + actual + "'");
assertEquals(expected, actual);
}
After a goup of whitespace is captured, it is checked whether it consists only of spaces, if yes then that goup is replaced by one single space, otherwise the goup consits of spaces and line terminators, in this case the group is replaced by one line terminator.
The output is:
'This is
a string.'
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 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());
}
}