Java StringUtils.stripEnd with period, hyphen or underscore - java

I'm trying to strip trailing characters off of a string using StringUtils.stripEnd, and noticed if I try to strip "_FOO" from "FOO_FOO", this returns an empty string. For example,
import org.apache.commons.lang3.StringUtils;
public class StripTest {
public static void printStripped(String s1, String suffix){
String result = StringUtils.stripEnd(s1, suffix);
System.out.println(String.format("Stripping '%s' from %s --> %s", suffix, s1, result));
}
public static void main(String[] args) {
printStripped("FOO.BAR", ".BAR");
printStripped("BAR.BAR", ".BAR");
printStripped("FOO_BAR", "_BAR");
printStripped("BAR_BAR", "_BAR");
printStripped("FOO-BAR", "-BAR");
printStripped("BAR-BAR", "-BAR");
}
}
Which outputs
Stripping '.BAR' from FOO.BAR --> FOO
Stripping '.BAR' from BAR.BAR -->
Stripping '_BAR' from FOO_BAR --> FOO
Stripping '_BAR' from BAR_BAR -->
Stripping '-BAR' from FOO-BAR --> FOO
Stripping '-BAR' from BAR-BAR -->
Can someone explain this behavior? Didn't see any examples from docs of this case. Using Java 7.

Look at the documentation and examples present in the StringUtils Javadoc:
Strips any of a set of characters from the end of a String.
A null input String returns null. An empty string ("") input returns the empty string.
If the stripChars String is null, whitespace is stripped as defined by Character.isWhitespace(char).
StringUtils.stripEnd(null, *) = null
StringUtils.stripEnd("", *) = ""
StringUtils.stripEnd("abc", "") = "abc"
StringUtils.stripEnd("abc", null) = "abc"
StringUtils.stripEnd(" abc", null) = " abc"
StringUtils.stripEnd("abc ", null) = "abc"
StringUtils.stripEnd(" abc ", null) = " abc"
StringUtils.stripEnd(" abcyx", "xyz") = " abc"
StringUtils.stripEnd("120.00", ".0") = "12"
This is not what you want, as it will strip the SET of characters anywhere from the end. I believe you are looking for removeEnd(...)
Removes a substring only if it is at the end of a source string, otherwise returns the source string.
A null source string will return null. An empty ("") source string will return the empty string. A null search string will return the source string.
StringUtils.removeEnd(null, *) = null
StringUtils.removeEnd("", *) = ""
StringUtils.removeEnd(*, null) = *
StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com"
StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
StringUtils.removeEnd("abc", "") = "abc"
removeEnd(...) operates not a set of characters, but instead a substring, which is what you are trying to extract.

Related

regex to get string in between slash of a url

In my website, user enters URL as http://mydomain/shirt/abc etc. I need to get abc as keyword (as logic given below). It's possible with String utils. I think regex would be easier, in which I am not good.
Java code
String testURLs[] = {"", "/" ,"/shirt", "/shirt/", "/shirt/abc", "/shirt/abc/", "/shirt/abc/xyz", "/shirt/abc?x=y", "/shirt/xyz/abc/pqr",
"abc/something", "/abc/some", "abc/shirt/something"};
for(String x : testURLs){
System.out.println(x + " --> " +getRelativeWebappURL(x));
}
private String getAppNameFromURL(String userEnteredURL){
String uri = userEnteredURL.replaceFirst("/shirt/","");
int index = uri.indexOf("/");
if(index == -1 || index == 0){
return null;
}
return uri.substring(0,index);
}
Output: (expected)
--> NULL
/ --> NULL
/shirt --> "" (empty string)
/shirt/ --> "" (empty string)
/shirt/abc --> abc
/shirt/abc/ --> abc
/shirt/abc/xyz --> abc
/shirt/abc?x=y --> abc
/shirt/xyz/abc/pqr --> xyz
abc/something --> NULL
/abc/some --> NULL
abc/shirt/something --> NULL
Literally, the expected logic is :
Get the string just after /shirt/
If starts with "" (empty string) - return NULL
If starts with "/" - return NULL
If starts with "/shirt/" - return "" (empty string)
If starts with "/shirt" - return "" (empty string)
If starts with "/shirt?" - return "" (empty string)
If starts with "/shirt/?" - return "" (empty string)
If starts with "/shirt/abc" - return abc
If starts with "/shirt/xyz/" - return xyz
If starts with "/shirt/xyz/abc" - return xyz
Is there any way to do this with regex ?
I tried in regex but failed!!
Yes it is!
shirt\/(\w+)
is what you need.
private String getAppNameFromURL(String userEnteredURL){
Pattern p = Pattern.compile("shirt\/(\w+)");
Matcher m = p.matcher(userEnteredURL);
if(m.find()){
return m.group(1);
}
return null;
}
This will always give you the first path parameter after shirt. If it is a word and does not start with a digit or any other non alphabetical character.
Also check this https://regexr.com/3o3jm
You can place your expected logic here to check the regex.
Thank you all for your time to help. At last I got an exact idea from all your inputs.
Here is a DEMO
private static String getAppNameFromURL(String userEnteredURL){
if(userEnteredURL!=null && !userEnteredURL.startsWith("/shirt")){
return null;
}
Pattern p = Pattern.compile("^/shirt/([^?]([^\\?/]+|.*))");
Matcher m = p.matcher(userEnteredURL);
if(m.find()){
return m.group(1);
}
return "";
}
Output:
empty string-->null
/-->null
/shirt--> empty string
/shirt/--> empty string
/shirt/abc-->abc
/shirt/abc/-->abc
/shirt/abc/xyz-->abc
/shirt/abc?x=y-->abc
/shirt/xyz/abc/pqr-->xyz
abc/something-->null
/abc/some-->null
abc/shirt/something-->null

Remove parts of String? [duplicate]

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

Parsing a String based on '$', as being used string seperator and may be used as the part of the value

"$1200-$2000$amol" -->{$1200-$2000, amol}.
"amol$$1200-$2000" -->{amol,$1200-$2000}.
"amol$1200-2000" -->{amol,1200-2000}.
"amol$$1200-$2000$patare" -->{amol,$1200-$2000,patare}.
"amol$$1200-$2000$patare$$12-$20" -->{amol,$1200-$2000,patare,$12-$20}.
Here, I am looking for the logic which will parse the string (left hand side) and result in a vector(right hand side). '$' is used as a seperator and '$' may be the part of the value for eg. second pattern "amol$$1200-$2000" here $ is seperator between "amol" and "$1200-$2000" as well as '$' is the part of value "$1200-$2000".
private Vector getTockensForLovValue(String lovValue) //...where lovValue is the string to be parsed {
int beginIndex = 0; Vector vector = new Vector();
while (beginIndex < lovValue.length())
{
int dollarIndex = lovValue.indexOf("$", beginIndex);
if (dollarIndex != -1)
{
String s1 = lovValue.substring(beginIndex, dollarIndex);
vector.add(s1);
beginIndex = dollarIndex + 1;
}
else
{
vector.add(lovValue.substring(beginIndex));
beginIndex = lovValue.length();
}
}
return vector;
}
UPDATE: The answer has been updated with an extended regex to also map amol$$1200$patare to {amol,$1200,patare} as request in comment.
You can use a regular expression to do this:
\$\d+(?:-\$\d+)?(?=\$|$)|[^$]+|(?<=^|\$)(?=\$|$)
It says: First try to match $99-$99 or $99. The match must be followed by $ or end-of-string.
If that fails, match a sequence of any character that is not $.
Also match the empty string between two $ or before leading $ or after trailing $.
When specified in a Java string literal, double the \.
private static List<String> parse(String input) {
Pattern p = Pattern.compile("\\$\\d+(?:-\\$\\d+)?(?=\\$|$)|[^$]+|(?<=^|\\$)(?=\\$|$)");
List<String> list = new ArrayList<>();
for (Matcher m = p.matcher(input); m.find(); )
list.add(m.group());
return list;
}
See regex101 for demo.
TEST
public static void main(String[] args) {
test("$1200-$2000$amol");
test("amol$$1200-$2000");
test("amol$1200-2000");
test("amol$$1200-$2000$patare");
test("amol$$1200-$2000$patare$$12-$20");
test("amol$$1200$patare");
test("$$$1200$$");
test("$$$1200x$$");
}
private static void test(String input) {
System.out.println(input + " --> " + parse(input));
}
OUTPUT
$1200-$2000$amol --> [$1200-$2000, amol]
amol$$1200-$2000 --> [amol, $1200-$2000]
amol$1200-2000 --> [amol, 1200-2000]
amol$$1200-$2000$patare --> [amol, $1200-$2000, patare]
amol$$1200-$2000$patare$$12-$20 --> [amol, $1200-$2000, patare, $12-$20]
amol$$1200$patare --> [amol, $1200, patare]
$$$1200$$ --> [, , $1200, , ]
$$$1200x$$ --> [, , , 1200x, , ]

Replace section on string in java

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);

Java : Replacing Last character of a String and First character of the String

I want to add Two java JSON String manually , so for this i need to remove "}" and replace it with comma "," of first JSON String and remove the first "{" of the second JSON String .
This is my program
import java.util.Map;
import org.codehaus.jackson.type.TypeReference;
public class Hi {
private static JsonHelper jsonHelper = JsonHelper.getInstance();
public static void main(String[] args) throws Exception {
Map<String, Tracker> allCusts = null;
String A = "{\"user5\":{\"Iden\":4,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1}}";
String B = "{\"user1\":{\"Iden\":4,\"Num\":1},\"user3\":{\"Iden\":6,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1}}";
String totalString = A + B;
if (null != totalString) {
allCusts = (Map<String, Tracker>) jsonHelper.toObject(
totalString, new TypeReference<Map<String, Tracker>>() {
});
}
System.out.println(allCusts);
}
}
When adding two Strings A + B
I want to remove the last character of "}" in A and replace it with "," and remove the FIrst character of "{" in B .
SO this should it look like .
String A = "{\"user5\":{\"Iden\":4,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1},";
String B = "\"user1\":{\"Iden\":4,\"Num\":1},\"user3\":{\"Iden\":6,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1}}";
I have tried
String Astr = A.replace(A.substring(A.length()-1), ",");
String Bstr = B.replaceFirst("{", "");
String totalString = Astr + Bstr ;
With this i was getting
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition
please suggest .
{ is a control character for Regular Expressions, and since replaceFirst takes a string representation of a Regular Expression as its first argument, you need to escape the { so it's not treated as a control character:
String Bstr = B.replaceFirst("\\{", "");
I would say that using the replace methods is really overkill here since you're just trying to chop a character off of either end of a string. This should work just as well:
String totalString = A.substring(0, A.length()-1) + "," + B.substring(1);
Of course, regex doesn't look like a very good tool for this. But the following seem to work:
String str = "{..{...}..}}";
str = str.replaceFirst("\\{", "");
str = str.replaceFirst("}$", ",");
System.out.println(str);
Output:
..{...}..},
Some issues in your first two statements. Add 0 as start index in substring method and leave with that. Put \\ as escape char in matching pattern and ut a , in second statement as replacement value.
String Astr = A.substring(0, A.length()-1);//truncate the ending `}`
String Bstr = B.replaceFirst("\\{", ",");//replaces first '{` with a ','
String totalString = Astr + Bstr ;
Please note: There are better ways, but I am just trying to correct your statements.

Categories

Resources