String s = "10.226.18.158:10.226.17.183:ABCD :AAAA"
My requirement is to split the string at up to 3rd : or up to 2nd :. i.e.
Something like String sa[] = s.split(), but with the regex splitting only up to 3rd or 2nd.
s[0] = "10.226.18.158"
s[1] = "10.226.17.183"
s[2] = "ABCD :AAAA"
According to the String#split() javadoc you can add a number to limit the number of splits.
s.split(":", 3);
Edit: as melwil metions This will return an array of up to the number passed in long.
So in your example of splitting up to 2nd : you would need to pass in 3.
s.split(":",3) returns the output
sa[0] = "10.226.18.158"
sa[1] = "10.226.17.183"
sa[2] = "ABCD :AAAA"
Relevent section quoted from the java doc about how the second argument (limit) works.
The limit parameter controls the number of times the pattern is
applied and therefore affects the length of the resulting array. If
the limit n is greater than zero then the pattern will be applied at
most n - 1 times, the array's length will be no greater than n, and
the array's last entry will contain all input beyond the last matched
delimiter. If n is non-positive then the pattern will be applied as
many times as possible and the array can have any length. If n is zero
then the pattern will be applied as many times as possible, the array
can have any length, and trailing empty strings will be discarded.
You can split your string basing on one non-whitespece character, \S{1}, followed by a colon, ::
String sa[] = s.split("\\S{1}:");
Related
If a string is a = 000102.45600. I need to convert it to a = ---102.45600.
Any help in java using either regex or String formatter?
Tried the following:
a = a.replaceFirst("^0+(?!$)","-");
but i am getting only a = -102.45600 not 3 dashes.
Rules: Any leading zeros before decimal in string should be replaced by that many dashes.
000023.45677 to ----23.45677
002345.56776 to --2345.56776
00000.45678 to -----.45678
Hopefully I am clear on what my need is?
String subjectString = "000102.45600";
String resultString = subjectString.replaceAll("\\G0", "-");
System.out.println(resultString); // prints ---102.45600
\G acts like \A (the start-of-string anchor) on the first iteration of replaceAll(), but on subsequent passes it anchors the match to the spot where the previous match ended. That prevents it from matching zeroes anywhere else in the string, like after the decimal point.
See: reference SO answer.
This should do it:
String number = //assign a value here
for (int i=number.length();i>0; i--) {
if (number.substring(0,i).matches("^0+$")) {
System.out.println(number.replaceAll("0","-"));
break;
}
}
This searches for the longest substring of number which starts at index 0 and consists entirely of zeroes - starting by checking the entire String, then shortening it until it finds the longest substring of leading zeroes. Once it finds this substring, it replaces each zero with a dash and breaks out of the loop.
Why not convert the start of the string to the "." to an integer, convert it back to a string then compare the lengths. 000102 length = 6. 102 length = 3. You would have your preceding zero count.
I am trying to fetch the string after the third slash. But i don' know how to do it. I have used split but that's not what I want.
for(String obj2: listKey.getCommonPrefixes()){
Map<String, String> map = new HashMap<String, String>();
String[] id = obj2.split("/");
if (id.length > 3) {
String name = id[3];
map.put("id", name);
map.put("date", "null");
map.put("size", String.valueOf(obj2.length()));
keys.add(map);
}
}
id[3] gives me only id[3] but i want everything after the third slash? how can i do that?
You can replace
String[] id = obj2.split("/");
by
String[] id = obj2.split("/", 4);
From the javadoc :
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Is there any difference between using split(regEx) and split(regEx, 0)?
Because the output is for the cases I tested the same. Ex:
String myS = this is stack overflow;
String[] mySA = myS.split(' ');
results in mySA === {'this','is','stack,'overflow'}
And
String myS = this is stack overflow;
String[] mySA = myS.split(' ', 0);
also results in mySA === {'this','is','stack,'overflow'}
Is there something "hidden" going on here? Or something else which needs to be known about the .split(regEx, 0)?
They are essentially the same.
Quoted from String.split(String regex) documentation:
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
Answering the question. Yes they're same.
Please find the split method of String class which intern calls the split(regex,0) method.
public String[] split(String regex) {
return split(regex, 0);
}
The limit parameter controls the number of times the pattern is
applied and therefore affects the length of the resulting array. If
the limit n is greater than zero then the pattern will be applied at
most n - 1 times, the array's length will be no greater than n, and
the array's last entry will contain all input beyond the last matched
delimiter. If n is non-positive then the pattern will be applied as
many times as possible and the array can have any length. If n is zero
then the pattern will be applied as many times as possible, the array
can have any length, and trailing empty strings will be discarded
For example the following code can give you some insight.
String myS = "this is stack overflow";
String[] mySA = myS.split(" ", 2);
String[] withOutLimit = myS.split(" ");
System.out.println(mySA.length); // prints 2
System.out.println(withOutLimit.length); // prints 4
I am trying to split a string using String split function, here's an example:
String[] list = " Hello ".split("\\s+");
System.out.println("String length: " + list.length);
for (String s : list) {
System.out.println("----");
System.out.println(s);
}
Here's the output:
String length: 2
----
----
Hello
As you can see, the leading whitespace becoming an empty element in the String array, but the trailing whitespace is not.
Does anyone know why?
You need to use the other split method which specifys the limit and specify a limit of -1
String[] list = " Hello ".split("\\s+", -1);
to preserve the trailing whitespace, - the default behavior is to omit the trailing spaces as per the javadoc
Edit (answer for comment):
To trim the leading space, you can strip off the leading space before splitting the String
String str = " Hello ".replaceAll("^\\s+", "");
String[] list = str.split("\\s+", -1);
From split documentation
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
so in reality split(regex) is the same as using
split(regex, 0);
and its documentation says
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
so if you want to include trailing empty strings will just have to use non-zero value like
split("\\s+",10);
but this will also limit result array to max 10 elements. To get rid of this problem use some negative number like
split("\\s+",-1);
For a given word, I want to search for all the substrings that appear next to each other at least 3 times, and replace all of them by only one. I know how to do this when the substring is only one character. For instance, the code below returns "Bah" for the input string "Bahhhhhhh":
String term = "Bahhhhhhh";
term = term.replaceAll("(.)\\1{2,}", "$1");
However, I need a more generic pattern that converts "Bahahahaha" into "Baha".
String[] terms = { "Bahhhhhhh", "Bahahahaha" };
for (String term : terms) {
System.out.println(term.replaceAll("(.+?)\\1{2,}", "$1"));
}
Output:
Bah
Baha
This will work for repetitions of 1, 2, or 3 characters long.
String term = "Bahhhhhhh";
term = term.replaceAll("(.{1,3})\\1{2,}", "$1");
You'll want to be careful to avoid huge backtracking performance hits. That's why I limited it to 1-3 characters.