0

I have few Java Strings like below:

ab-android-regression-4.4-git
ab-ios-regression-4.4-git
ab-tablet-regression-4.4-git

However, I do not want such lengthy and unwanted names and so I want to get rid of starting ab- and ending -git part. The pattern for all the Strings is the same (starts with ab and ends with git)

Is there a function/class in Java that will help me in trimming such things? For example, something like:

String test = "ab-android-regression-4.4-git";
test.trim(ab, git)

Also, can StringUtils class help me with this? Thoughts on regular expressions?

EDITED PART: I also want to know how to eliminate the - characters in the Strings and change everything to uppercase letters

4 Answers 4

2

Here's a method that's more general purpose to remove a prefix and suffix from a string:

public static String trim (String str, String prefix, String suffix)
{
    int indexOfLast = str.lastIndexOf(suffix);

    // Note: you will want to do some error checking here 
    // in case the suffix does not occur in the passed in String

    str = str.substring(0, indexOfLast);

    return str.replaceFirst(prefix, "");
}

Usage:

String test = "ab-android-regression-4.4-git";
String trim = trim(test, "ab-", "-git"));

To remove the "-" and make uppercase, then just do:

trim = trim.replaceAll("-", " ").toUpperCase();
Sign up to request clarification or add additional context in comments.

Comments

2

You can use test = test.replace("ab-", "") and similar for the "-git" or you can use test = StringUtils.removeStart(test, "ab-") and similarly, removeEnd.

I prefer the latter if you can use StringUtils because it won't ever accidentally remove the middle of the filename if those expressions are matched.

2 Comments

Thanks, I just edited my question to eliminate more data and change to uppercase letters.
If you want spaces instead of hyphens, use test.replaceAll("-"," "). If you want no spaces use test.replaceAll("-",""). If you want all uppercase letters, use test.toUpperCase(). If you want real capital casing on each word, you'll need to do some of your own logic.
1

Since the parts to trim are constant in size, you should simply use substring :

yourString.substring(3, yourString.length - 4)

1 Comment

Thanks, I just edited my question to eliminate more data and change to uppercase letters.
0

If your string always contains ab- at the begining and -git at the end then here is the code

String test = "ab-android-regression-4.4-git";
test=test.substring(3, s.length() - 4);
System.out.println("s is"+s);  //output is android-regression-4.4

To know more about substrings click https://docs.oracle.com/javase/tutorial/java/data/manipstrings.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.