Does anyone knows how to replace the last word in a String.
Currently I am doing:
someStr = someStr.replace(someStr.substring(someStr.lastIndexOf(" ") + 1), "New Word");
The above code replaces every single occurance of the word in the string.
Thanks.
You could create a new string "from scratch" like this:
someStr = someStr.substring(0, someStr.lastIndexOf(" ")) + " New Word";
Another option (if you really want to use "replace" :) is to do
someStr = someStr.replaceAll(" \\S*$", " New Word");
replaceAll uses regular expressions and \S*$ means a space, followed by some non-space characters, followed by end of string. (That is, replace the characters after the last space.)
You're not far from the solution. Just keep the original string until the last index of " ", and append the new word to this substring. No need for replace here.
What your code is doing is replacing the substring by "New word".
Instead you need to substring first, and then do a replace on that string.
Here's how I would do it
someStr = someStr.substring(0, someStr.lastIndexOf(" ") + 1) + "New word"
try:
someStr = someStr.substring( someStr.lastIndexOf(" ") ) + " " + new_word;
use this: someStr.substring(0, someStr.lastIndexOf(" ")) + "New Word".
You can also use regular expression, e.g. someStr.repalaceFirst("\s+\S+$", " " + "New Word")
Try this regex (^.+)b(.+$)
Example (Replace the last b character)
System.out.println("1abchhhabcjjjabc".replaceFirst("(^.+)b(.+$)", "$1$2"));
Related
I need to replace:
myVariable = "sample string is long " +
"so I put rest of it in 2nd line." +
" And sometimes in 3rd and so on";
with:
myVariable = "sample string is long so I put rest of it in 2nd line. And sometimes in 3rd and so on";
Additional issue: how to merge entities like above I they have other variables in concatenation chain?
myVar = "The number of the beast is " + numberOfTheBeast + " !!! So I said";
What I'd like to do is to change it into single string with params inside.
I'm not a regular expression guru, but these three regex replaces should do the trick. Most IDEs have a regex replace function.
Replace: With:
\s*\+\s*\n + (space, plus, space)
"\s*\+\s*" nothing
\s*\+\s* + (space, plus, space)
You might have to use \s*+\s*\r\n for the first regex, if you are on Windows.
I'm making a simple program that will deal with equations from a String input of the equation
When I run it, however, I get an exception because of trying to replace the " +" with a " +" so i can split the string at the spaces. How should I go about using
the string replaceAll method to replace these special characters? Below is my code
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+
^
public static void parse(String x){
String z = "x^2+2=2x-1";
String[] lrside = z.split("=",4);
System.out.println("Left side: " + lrside[0] + " / Right Side: " + lrside[1]);
String rightside = lrside[0];
String leftside = lrside[1];
rightside.replaceAll("-", " -");
rightside.replaceAll("+", " +");
leftside.replaceAll("-", " -"); leftside.replaceAll("+", " +");
List<String> rightt = Arrays.asList(rightside.split(" "));
List<String> leftt = Arrays.asList(leftside.split(" "));
System.out.println(leftt);
System.out.println(rightt);
replaceAll accepts a regular expression as its first argument.
+ is a special character which denotes a quantifier meaning one or more occurrences. Therefore it should be escaped to specify the literal character +:
rightside = rightside.replaceAll("\\+", " +");
(Strings are immutable so it is necessary to assign the variable to the result of replaceAll);
An alternative to this is to use a character class which removes the metacharacter status:
rightside = rightside.replaceAll("[+]", " +");
The simplest solution though would be to use the replace method which uses non-regex String literals:
rightside = rightside.replace("+", " +");
I had similar problem with regex = "?". It happens for all special characters that have some meaning in a regex. So you need to have "\\" as a prefix to your regex.
rightside = rightside.replaceAll("\\+", " +");
String#replaceAll expects regex as input, and + is not proper pattern, \\+ would be pattern. rightside.replaceAll("\\+", " +");
The reason behind this is - There are reserved characters for regex. So when you split them using the java split() method, You will have to use them with escape.
FOr example you want to split by + or * or dot(.) then you will have to do it as split("\+") or split("\*") or split("\.") according to your need.
The reason behind my long explanation on regex is -
YOU MAY FACE IT in OTHER PLACES TOO.
For example the same issue will occur if you use replace or replaceAll methods of java Because they are also working based on regex.
I have this code
lStock.setText(" Put " + getLoc(i));
At the moment it prints out like this on the GUI:
3I031C
what I want to show now on the screen GUI is:
3I03-1C
I tried testing the split() but I'm confused.
String.split is used to break apart a string based on some particular delimiter. You don't have a delimiter here.
If you always want to break after the fourth character:
String str = "3I031C";
String out = str.substring(0, 4) + '-' + str.substring(4);
You can't use the split method since it needs a delimiter, but you're string doesn't contain any.
You can try using substring:
str = str.substring(0, 4) + "-" + str.substring(4);
But this will only work if the string always have the same length and format.
If its a fixed output try like below
s = s.substring(0, 4) + "-" + s.substring(4);
refer to String.substring()
I have a string that contains some text followed by a blank line. What's the best way to keep the part with text, but remove the whitespace newline from the end?
Use String.trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.
String trimmedString = myString.trim();
String.replaceAll("[\n\r]", "");
This Java code does exactly what is asked in the title of the question, that is "remove newlines from beginning and end of a string-java":
String.replaceAll("^[\n\r]", "").replaceAll("[\n\r]$", "")
Remove newlines only from the end of the line:
String.replaceAll("[\n\r]$", "")
Remove newlines only from the beginning of the line:
String.replaceAll("^[\n\r]", "")
tl;dr
String cleanString = dirtyString.strip() ; // Call new `String::string` method.
String::strip…
The old String::trim method has a strange definition of whitespace.
As discussed here, Java 11 adds new strip… methods to the String class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace.
Example code.
String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");
Or you can strip just the leading or just the trailing whitespace.
You do not mention exactly what code point(s) make up your newlines. I imagine your newline is likely included in this list of code points targeted by strip:
It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').
It is '\t', U+0009 HORIZONTAL TABULATION.
It is '\n', U+000A LINE FEED.
It is '\u000B', U+000B VERTICAL TABULATION.
It is '\f', U+000C FORM FEED.
It is '\r', U+000D CARRIAGE RETURN.
It is '\u001C', U+001C FILE SEPARATOR.
It is '\u001D', U+001D GROUP SEPARATOR.
It is '\u001E', U+001E RECORD SEPARATOR.
It is '\u001F', U+0
If your string is potentially null, consider using StringUtils.trim() - the null-safe version of String.trim().
If you only want to remove line breaks (not spaces, tabs) at the beginning and end of a String (not inbetween), then you can use this approach:
Use a regular expressions to remove carriage returns (\\r) and line feeds (\\n) from the beginning (^) and ending ($) of a string:
s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "")
Complete Example:
public class RemoveLineBreaks {
public static void main(String[] args) {
var s = "\nHello world\nHello everyone\n";
System.out.println("before: >"+s+"<");
s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
System.out.println("after: >"+s+"<");
}
}
It outputs:
before: >
Hello world
Hello everyone
<
after: >Hello world
Hello everyone<
I'm going to add an answer to this as well because, while I had the same question, the provided answer did not suffice. Given some thought, I realized that this can be done very easily with a regular expression.
To remove newlines from the beginning:
// Trim left
String[] a = "\n\nfrom the beginning\n\n".split("^\\n+", 2);
System.out.println("-" + (a.length > 1 ? a[1] : a[0]) + "-");
and end of a string:
// Trim right
String z = "\n\nfrom the end\n\n";
System.out.println("-" + z.split("\\n+$", 2)[0] + "-");
I'm certain that this is not the most performance efficient way of trimming a string. But it does appear to be the cleanest and simplest way to inline such an operation.
Note that the same method can be done to trim any variation and combination of characters from either end as it's a simple regex.
Try this
function replaceNewLine(str) {
return str.replace(/[\n\r]/g, "");
}
String trimStartEnd = "\n TestString1 linebreak1\nlinebreak2\nlinebreak3\n TestString2 \n";
System.out.println("Original String : [" + trimStartEnd + "]");
System.out.println("-----------------------------");
System.out.println("Result String : [" + trimStartEnd.replaceAll("^(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])|(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])$", "") + "]");
Start of a string = ^ ,
End of a string = $ ,
regex combination = | ,
Linebreak = \r\n|[\n\x0B\x0C\r\u0085\u2028\u2029]
Another elegant solution.
String myString = "\nLogbasex\n";
myString = org.apache.commons.lang3.StringUtils.strip(myString, "\n");
For anyone else looking for answer to the question when dealing with different linebreaks:
string.replaceAll("(\n|\r|\r\n)$", ""); // Java 7
string.replaceAll("\\R$", ""); // Java 8
This should remove exactly the last line break and preserve all other whitespace from string and work with Unix (\n), Windows (\r\n) and old Mac (\r) line breaks: https://stackoverflow.com/a/20056634, https://stackoverflow.com/a/49791415. "\\R" is matcher introduced in Java 8 in Pattern class: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html
This passes these tests:
// Windows:
value = "\r\n test \r\n value \r\n";
assertEquals("\r\n test \r\n value ", value.replaceAll("\\R$", ""));
// Unix:
value = "\n test \n value \n";
assertEquals("\n test \n value ", value.replaceAll("\\R$", ""));
// Old Mac:
value = "\r test \r value \r";
assertEquals("\r test \r value ", value.replaceAll("\\R$", ""));
String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");
I had a look at other stackoverflow questions and couldn't find one that asked the same question, so here it is:
How do you match the first and last characters of a string (can be multi-line or empty).
So for example:
String = "this is a simple sentence"
Note that the string includes the beginning and ending quotation marks.
How do I get match the first and last characters where the string begins and ends with a quotation mark (").
I tried:
^"|$" and \A"\Z"
but these do not produce the desired result.
Thanks for your help in advance :)
Is this what you are looking for?
String input = "\"this is a simple sentence\"";
String result = input.replaceFirst("(?s)^\"(.*)\"$", " $1 ");
This will replace the first and last character of the input string with spaces if it starts and ends with ". It will also work across multiple lines since the DOTALL flag is specified by (?s).
The regex that matches the whole input ".*". In java, it looks like this:
String regex = "\".*\"";
System.out.println("\"this is a simple sentence\"".matches(regex)); // true
System.out.println("this is a simple sentence".matches(regex)); // false
System.out.println("this is a simple sentence\"".matches(regex)); // false
If you want to remove the quotes, use this:
String input = "\"this is a simple sentence\"";
input = input.replaceAll("(^\"|\"$)", "")); // this is a simple sentence (without any quotes)
If you want this to work over multiple lines, use this:
String input = "\"this is a simple sentence\"\n\"and another sentence\"";
System.out.println(input + "\n");
input = input.replaceAll("(?m)(^\"|\"$)", "");
System.out.println(input);
which produces output:
"this is a simple sentence"
"and another sentence"
this is a simple sentence
and another sentence
Explanation of regex (?m)(^"|"$):
(?m) means "Caret and dollar match after and before newlines for the remainder of the regular expression"
(^"|"$) means ^" OR "$, which means "start of line then a double quote" OR "double quote then end of line"
Why not use the simple logic of getting the first and last characters based on charAt method of String? Place a few checks for empty/incomplete strings and you should be done.
String regexp = "(?s)\".*\"";
String data = "\"This is some\n\ndata\"";
Matcher m = Pattern.compile(regexp).matcher(data);
if (m.find()) {
System.out.println("Match starts at " + m.start() + " and ends at " + m.end());
}