Java 8's String.replaceAll(regexStr, replacementStr) doesn't work when the regex given is ".*". The result is double the replacementStr. For example:
String regexStr = ".*";
String replacementStr = "REPLACEMENT"
String initialStr = "hello";
String finalStr = initialStr.replaceAll(regexStr, replacementStr);
// Expected Result: finalStr == "REPLACEMENT"
// Actual Result: finalStr == "REPLACEMENTREPLACEMENT"
I know replaceAll() doesn't exactly make sense to use when the regex is ".*", but the regex isn't hardcoded and could be other regex strings. Why doesn't this work? Is it a bug in Java 8?
// specify start and end of line
String regexStr = "^.*$";
String replacementStr = "REPLACEMENT"
String initialStr = "hello";
String finalStr = initialStr.replaceAll(regexStr, replacementStr);
Related
I want to remove a part of string from one character, that is:
Source string:
manchester united (with nice players)
Target string:
manchester united
There are multiple ways to do it. If you have the string which you want to replace you can use the replace or replaceAll methods of the String class. If you are looking to replace a substring you can get the substring using the substring API.
For example
String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));
To replace content within "()" you can use:
int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));
String Replace
String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");
Edit:
By Index
s = s.substring(0, s.indexOf("(") - 1);
Use String.Replace():
http://www.daniweb.com/software-development/java/threads/73139
Example:
String original = "manchester united (with nice players)";
String newString = original.replace(" (with nice players)","");
originalString.replaceFirst("[(].*?[)]", "");
https://ideone.com/jsZhSC
replaceFirst() can be replaced by replaceAll()
Using StringBuilder, you can replace the following way.
StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");
You should use the substring() method of String object.
Here is an example code:
Assumption: I am assuming here that you want to retrieve the string till the first parenthesis
String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);
I would at first split the original string into an array of String with a token " (" and the String at position 0 of the output array is what you would like to have.
String[] output = originalString.split(" (");
String result = output[0];
Using StringUtils from commons lang
A null source string will return null. An empty ("") source string will return the empty string. A null remove string will return the source string. An empty ("") remove string will return the source string.
String str = StringUtils.remove("Test remove", "remove");
System.out.println(str);
//result will be "Test"
If you just need to remove everything after the "(", try this. Does nothing if no parentheses.
StringUtils.substringBefore(str, "(");
If there may be content after the end parentheses, try this.
String toRemove = StringUtils.substringBetween(str, "(", ")");
String result = StringUtils.remove(str, "(" + toRemove + ")");
To remove end spaces, use str.trim()
Apache StringUtils functions are null-, empty-, and no match- safe
Kotlin Solution
If you are removing a specific string from the end, use removeSuffix (Documentation)
var text = "one(two"
text = text.removeSuffix("(two") // "one"
If the suffix does not exist in the string, it just returns the original
var text = "one(three"
text = text.removeSuffix("(two") // "one(three"
If you want to remove after a character, use
// Each results in "one"
text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")
You can also check out removePrefix, removeRange, removeSurrounding, and replaceAfterLast which are similar
The Full List is here: (Documentation)
// Java program to remove a substring from a string
public class RemoveSubString {
public static void main(String[] args) {
String master = "1,2,3,4,5";
String to_remove="3,";
String new_string = master.replace(to_remove, "");
// the above line replaces the t_remove string with blank string in master
System.out.println(master);
System.out.println(new_string);
}
}
You could use replace to fix your string. The following will return everything before a "(" and also strip all leading and trailing whitespace. If the string starts with a "(" it will just leave it as is.
str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched
I tried to split a string using string.Index and string.length but I get an error that string is out of range. How can I fix that?
while (in.hasNextLine()) {
String temp = in.nextLine().replaceAll("[<>]", "");
temp.trim();
String nickname = temp.substring(temp.indexOf(' '));
String content = temp.substring(' ' + temp.length()-1);
System.out.println(content);
Use the java.lang.String split function with a limit.
String foo = "some string with spaces";
String parts[] = foo.split(" ", 2);
System.out.println(String.format("cr: %s, cdr: %s", parts[0], parts[1]));
You will get:
cr: some, cdr: string with spaces
Must be some around this:
String nickname = temp.substring(0, temp.indexOf(' '));
String content = temp.substring(temp.indexOf(' ') + 1);
string.split(" ",2)
split takes a limit input restricting the number of times the pattern is applied.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)
String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex.
But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.
I have this section of code
String string = "somestring";
String str2 = "str";
String str3 = "xxx"
if ( string.match("(.*)" + str2 + "(.*)") ) {
//
}
result = somxxxing
how can i replace that section of string with str3?
i need this to work for every strings
Check out the javadoc for java.lang.String.
You're probably looking for String.replace(CharSequence target, CharSequence replacement), which replaces every occurrence of target with replacement.
e.g.
result = string.replace(str2, str3);
EDIT :
Goal : http://localhost:8080/api/upload/form/test/test
Is it possible to have some thing like `{a-b, A-B..0-9}` kind of pattern and match them and replace with value.
i have following string
http://localhost:8080/api/upload/form/{uploadType}/{uploadName}
there can be any no of strings like {uploadType}/{uploadName}.
how to replace them with some values in java?
[Edited] Apparently you don't know what substitutions you'll be looking for, or don't have a reasonable finite Map of them. In this case:
Pattern SUBST_Patt = Pattern.compile("\\{(\\w+)\\}");
StringBuilder sb = new StringBuilder( template);
Matcher m = SUBST_Patt.matcher( sb);
int index = 0;
while (m.find( index)) {
String subst = m.group( 1);
index = m.start();
//
String replacement = "replacement"; // .. lookup Subst -> Replacement here
sb.replace( index, m.end(), replacement);
index = index + replacement.length();
}
Look, I'm really expecting a +1 now.
[Simpler approach] String.replace() is a 'simple replace' & easy to use for your purposes; if you want regexes you can use String.replaceAll().
For multiple dynamic replacements:
public String substituteStr (String template, Map<String,String> substs) {
String result = template;
for (Map.Entry<String,String> subst : substs.entrySet()) {
String pattern = "{"+subst.getKey()+"}";
result = result.replace( pattern, subst.getValue());
}
return result;
}
That's the quick & easy approach, to start with.
You can use the replace method in the following way:
String s = "http://localhost:8080/api/upload/form/{uploadType}/{uploadName}";
String typevalue = "typeValue";
String nameValue = "nameValue";
s = s.replace("{uploadType}",value).replace("{uploadName}",nameValue);
You can take the string that start from {uploadType} till the end.
Then you can split that string using "split" into string array.
Were the first cell(0) is the type and 1 is the name.
Solution 1 :
String uploadName = "xyz";
String url = "http://localhost:8080/api/upload/form/" + uploadName;
Solution 2:
String uploadName = "xyz";
String url = "http://localhost:8080/api/upload/form/{uploadName}";
url.replace("{uploadName}",uploadName );
Solution 3:
String uploadName = "xyz";
String url = String.format("http://localhost:8080/api/upload/form/ %s ", uploadName);
String s = "http://localhost:8080/api/upload/form/{uploadType}/{uploadName}";
String result = s.replace("uploadType", "UploadedType").replace("uploadName","UploadedName");
EDIT: Try this:
String r = s.substring(0 , s.indexOf("{")) + "replacement";
The UriBuilder does exactly what you need:
UriBuilder.fromPath("http://localhost:8080/api/upload/form/{uploadType}/{uploadName}").build("foo", "bar");
Results in:
http://localhost:8080/api/upload/form/foo/bar
This is just an example code of the thing i try to accomplish.
String s = "hello(1234aA)something";
String replaceString = "(1234aa)";
String s2 = s.replaceAll("(i?)" + replaceString, "something");
The String s is going to be the same but can differ in case, thats why i use (i?) in replaceall.
How can i make regex ignore the special
Use quote(), it seems you've already figured out the ignore case, but you should use (?i), not (i?).
String s = "hello(1234aA)something";
String replaceString = "(?i)" + Pattern.quote("(1234aa)");
String s2 = s.replaceAll(replaceString, "something");
This should work.