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
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();
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.
Since the parts to trim are constant in size, you should simply use substring :
yourString.substring(3, yourString.length - 4)
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
Related
program test
so I have a program that will be given two strings as arguments: base and remove. It has to take out remove from base. I am using the split method to remove the second string from the first. However, the case on the chars of the second string should not matter, while the case of the first string must be preserved. I found a lot of ways to do this when you define the remove string in the program as a String literal: I can use ?i for example, but because remove is coming in as an argument and not a literal that I am defining in the program, this isn't working. Please check my attached picture so that you can see exactly where this is failing. Appreciate the help.
public String withoutString(String base, String remove) {
String array[] = base.split(remove);
String result = "";
for(int i = 0; i<array.length;i++)
result+= array[i];
return result;
}
Use a regex pattern with CASE_INSENSITIVE and LITERAL flags:
return Pattern.compile(remove, Pattern.CASE_INSENSITIVE | Pattern.LITERAL)
.matcher(base).replaceAll("");
String.replaceAll() method accepts regex you can use directly like:
return base.replaceAll("(?i)(" + remove +")[\s]*", "")
How can I delete everything after first empty space in a string which user selects? I was reading this how to remove some words from a string in java. Can this help me in my case?
You can use replaceAll with a regex \s.* which match every thing after space:
String str = "Hello java word!";
str = str.replaceAll("\\s.*", "");
output
Hello
regex demo
Like #Coffeehouse Coder mention in comment, This solution will replace every thing if the input start with space, so if you want to avoid this case, you can trim your input using string.trim() so it can remove the spaces in start and in end.
Assuming that there is no space in the beginning of the string.
Follow these steps-
Split the string at space. It will create an array.
Get the first element of that array.
Hope this helps.
str = "Example string"
String[] _arr = str.split("\\s");
String word = _arr[0];
You need to consider multiple white spaces and space in the beginning before considering the above code.
I am not native to JAVA Programming but have an idea that it has split function for string.
And the reference you cited in the question is bit complex, while you can achieve the desired thing very easily.
P.S. In future if you make a mind to get two words or three, splitting method is better (assuming you have already dealt with multiple white-spaces) else substring is better.
A simple way to do it can be:
System.out.println("Hello world!".split(" ")[0]);
// Taking 'str' as your string
// To remove the first space(s) of the string,
str = str.trim();
int index = str.indexOf(" ");
String word = str.substring(0, index);
This is just one method of many.
str = str.replaceAll("\\s+", " "); // This replaces one or more spaces with one space
String[] words = str.split("\\s");
String first = words[0];
The simplest solution in my opinion would be to just locate the index which the user wants it to be cut off at and then call the substring() method from 0 to the index they wanted. Set that = to a new string and you have the string they want.
If you want to replace the string then just set the original string = to the result of the substring() method.
Link to substring() method: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)
There are already 5 perfectly good answers, so let me add a sixth one. Variety is the spice of life!
private static final Pattern FIRST_WORD = Pattern.compile("\\S+");
public static String firstWord(CharSequence text) {
Matcher m = FIRST_WORD.matcher(text);
return m.find() ? m.group() : "";
}
Advantages over the .split(...)[0]-type answers:
It directly does exactly what is being asked, i.e. "Find the first sequence of non-space characters." So the self-documentation is more explicit.
It is more efficient when called on multiple strings (e.g. for batch processing a large list of strings) because the regular expression is compiled only once.
It is more space-efficient because it avoids unnecessarily creating a whole array with references to each word when we only need the first.
It works without having to trim the string.
(I know this is probably too late to be of any use to the OP but I'm leaving it here as an alternative solution for future readers.)
This would be more efficient
String str = "Hello world!";
int spaceInd = str.indexOf(' ');
if(spaceInd != -1) {
str = str.substring(0, spaceInd);
}
System.out.println(String.format("[%s]", str));
I have a string that it can contains commas, but not only commas.
For example:
"," is wrong
"hello, my dear" is right
",,,," is wrong
",,hello" is right
For this reason I don't think I can use regex. How could I test this situation avoiding simple comparison like this one?
myString.equals(",") || myString.equals(",,") || ....
The easiest solution, IMHO, would be to stream the characters, and check that they are all ',':
boolean onlyCommas = myString.chars().allMatch(c -> c == ',');
A regex is actually what you're looking for:
boolean result = myString.matches("^,+$");
^ represents the beginning of the string, $ represents the end of the string and ,+ matches only (and at least one) comma characters. This way you match any string that only consists of comma characters.
String replacedString = someString.replace(",", "");
If it was made up of just commas the string will be empty afterwards.
I want to match certain group of characters in a String independent of their order in the String using regex fucntion. However, the only requirement is that they all must be there.
I have tried
String elD = "15672";
String t = "12";
if ((elD.matches(".*[" + t + "].*"))) {
System.out.println(elD);
}
This one checks whether any of the characters are present. But I want all of them to be there.
Also I tried
String elD = "15672";
String t = "12";
if ((elD.matches(".*(" + t + ").*"))) {
System.out.println(elD);
}
This does not work as well. I have searched quite a while but I could not find an example when all of the characters from the pattern must be present in the String independent of their order.
Thanks
You can write regex for this but it would not look nice. If you would want to check if your string contains anywhere x and y you would need to use few times look-ahead like
^(?=.*x)(?=.*y).*$
and use it like
yourStirng.matches(regex);
But this way you would need to create your own method which would generate you dynamic regex and add (?=.*X) for each character you want to check. You would also need to make sure that this character is not special in regex like ? or +.
Simpler and not less effective solution would be creating your own method which would check if your string contains all searched characters, something like
public static boolean containsUnordered(String input, String searchFor){
char[] characters = searchFor.toCharArray();
for (char c: characters)
if (!input.contains(String.valueOf(c)))
return false;
return true;
}
You can built a pattern from the search string using the replaceAll method:
String s = "12";
String pattern = s.replaceAll("(.)", "(?=[^$1]*$1)");
Note: You can't test the same character several times. (i.e. 112 gives (?=[^1]*1)(?=[^1]*1)(?=[^2]*2) that is exactly the same as (?=[^1]*1)(?=[^2]*2))
But in my opinion Pshemo method is probably more efficient.
I was wondering what would be the best way to go about removing characters before a comma in a string, as well as removing the comma itself, leaving just the characters after the comma in the string, if the string is represented as 'city,country'.
Thanks in advance
So you want
city,country
to become
country
An easy way to do this is this:
public static void main(String[] args) {
System.out.println("city,country".replaceAll(".*,", ""));
}
This is "greedy" though, meaning it will change
city,state,country
into
country
In your case, you might want it to become
state,country
I couldn't tell from your question.
If you want "non-greedy" matching, use
System.out.println("city,state,country".replaceAll(".*?,", ""));
this will output
state, country
check this
String s="city,country";
System.out.println(s.substring(s.lastIndexOf(',')+1));
I found it faster than .replaceAll(".*,", "")
If what you are interested in is extracting data while leaving the original string intact you should use the split(String regex) function.
String foo = new String("city,country");
String[] data = foo.split(",");
The data array will now contain strings "city" and "country".
More info is available here: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29
This can be done with a combination of substring and indexOf, using indexOf to determine the position of the (first) comma, and substring to extract a portion of the string relative to that position.
String s = "city,country";
String s2 = s.substring(s.indexOf(",") + 1);
You could implement a sort of substring that finds all the indexes of characters before your comma and then all you'd need to do is remove them.