String str = "[[28.667949,77.287067,232,0,0.8,5],[28.667949,77.287067,232,0,0.8,5]]";
I have a String, and want to convert it into any type either in Array,List or Object except String.
Expected Output :
List/Array/Object =
[[28.667949,77.287067,232,0,0.8,5],[28.667949,77.287067,232,0,0.8,5]]
you have to do
List ls = Arrays.asList(str.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
There is work around for this
1.) First replace all '[' and ']' with ""
str = str.replaceAll("[","");
str = str.replaceAll("]","");
2.)Then u can split the string with ","
which gives u an array.
String[] split = str.split(",");
If groups of data is important, here's an algo:
1. create new List<List<String>> strList
2. String [] strs= str.split("],")
3. loop each str in strs
3.1 replace all existence of "[" and "]" of str
3.2 strList.add(Arrays.asList(str.split(",")))
Hope this helps!
Related
How to transform a string with this format into a list?
[[["Census_county_divisions","Populated_places_in_the_United_States","Populated_places_by_country","Geography_by_country","Geography_by_place","Geography","Main_topic_classifications"]],[["example","text","thanks"]],[["name","surname","age"]]]
From that string I would like to have 3 lists:
List 1:
"Census_county_divisions","Populated_places_in_the_United_States","Populated_places_by_country","Geography_by_country","Geography_by_place","Geography","Main_topic_classifications"
List 2:"example","text","thanks"
List 3:"name","surname","age"
I have tried different approachs do process this string, with split, with method StringUtils.substringBetween, with indexOf, with regex, with Json Parser.... I always get an error, is it an easier way out??
Comments: I don't see this string as a Json format, since the Json format would be "name":"John", If I'm wrong, please let me know how I could process it as a Json....
I have tried also with JsonParser and had the Exception in thread "main" java.lang.IllegalStateException: Not a JSON Object:
[[["Census_county_divisions","Popula
I write this code:
remove the [[[,]]] strings
replace the ]],[[ for | character
split the string
///The String to convert
String arg = "[[[\"Census_county_divisions\",....
[[\"example\",\"text\",\"thanks\"]],[[\"name\",\"surname\",\"age\"]]]";
System.out.println(arg);
////Replace
arg = arg.replace("[[[", "");
arg = arg.replace("]],[[", "|");
arg = arg.replace("]]]", "");
System.out.println(arg);
////Split
String[] array=arg.split("\\|");
List<String> list = Arrays.asList(array);
///Verify
for(String s: list) {
System.out.println(s);
}
Regards
This worked for me. I only trimmed the start and end character set and then split it into 3 different strings which yielded the lists.
str = new StringBuilder(str).replace(0, 4, "")
.reverse().replace(0, 4, "")
.reverse()
.toString();
String[] arr1 = str.split("\"\\]\\],\\[\\[\"");
List<String> list1 = Arrays.asList(arr1[0]
.split("\",\""));
List<String> list2 = Arrays.asList(arr1[1]
.split("\",\""));
List<String> list3 = Arrays.asList(arr1[2]
.split("\",\""));
Maybe you could use Regex to extract everything inside the "[[" "]]" and trimming the "[" and "]" at the start and the end of each group. After that, you could split the result and put it into a List.
Here a simple example:
List<List<String>> lists = new ArrayList<>();
String string = "[[[\"Census_cunty_divisions\",\"Populated_places_in_the_United_States\",\"Populated_places_by_country\",\"Geography_by_country\",\"Geography_by_place\",\"Geography\",\"Main_topic_classifications\"]],[[\"example\",\"text\",\"thanks\"]],[[\"name\",\"surname\",\"age\"]]]";
Pattern pattern = Pattern.compile("\\[\\[(.*?)\\]\\]");
Matcher matcher = pattern.matcher(string);
String proccesed;
while (matcher.find()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
proccesed = StringUtils.strip(matcher.group(i), "[");
proccesed = StringUtils.strip(proccesed, "]");
lists.add(Arrays.asList(proccesed.split(",")));
}
}
int i = 0;
for(List<String> stringList : lists){
System.out.printf("List # %s \n", i);
for(String elementOfList:stringList){
System.out.printf("Element %s \n", elementOfList);
}
i++;
}
Here you will have a dynamic list depending on the initial String.
I've used the org.apache.commons commons-text library to strip the matches.
I hope it's useful.
I have a string containing numbers separated with ,. I want to remove the , before the first character.
The input is ,1,2,3,4,5,6,7,8,9,10, and this code does not work:
results.replaceFirst(",","");
Strings are immutable in Java. Calling a method on a string will not modify the string itself, but will instead return a new string.
In order to capture this new string, you need to assign the result of the operation back to a variable:
results = results.replaceFirst(",", "");
Try this
String str = ",1,2,3,4,5,6,7,8,9,10";
str = str .startsWith(",") ? str .substring(1) : str ;
System.out.println("output"+str); // 1,2,3,4,5,6,7,8,9,10
you can also do like this ..
String str = ",1,2,3,4,5,6,7,8,9,10";
String stre = str.replaceFirst("^,", "");
Log.e("abd",stre);
Try this
String str = ",1,2,3,4,5,6,7,8,9,10";
if(Objects.nonNull(str) && str.startsWith(",")){
str = str.substring(1, str.length());
}
it will remove , at first position
I got a String:
["4fd1cf1783353a15415","4ffecf87fcc40d110a965626"]
or
["4fd5f684815345","4fd6ef3e60a676854651","4fd83c33c19164512153"]
And I'd like to store every id (eg. 4fd5f684815345, 4fd6ef3e60a676854651, 4fd83c33c19164512153...) in a independant String (or ArrayList).
How to parse it, because the String can be dynamic (1,2,3 values or more)?
OR JSON Array Parsing:
My JSON
"idCards":[
"4fc52f95egvt418541515",
"4fd1d05454151541545115"
],
A part of my code:
msg3 = (JSONArray) myobject.get("idCards");
System.out.println(msg3.toJSONString());
The result:
[4fc52f95egvt418541515","4fd1d05454151541545115"]
I'd like this 2 values in 2 differents String.
Many thanks for your help!
It would appear to be that this could be a JSON String. In which case, you may make use of a Java JSON Library to help you parse that into Java native objects.
http://www.json.org/
http://code.google.com/p/google-gson/
String data = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
// parse JSON String to JSON Array
JsonArray array = (JsonArray) (new JsonParser()).parse(data);
// build a Java ArrayList
List<String> stringList = new ArrayList<String>();
// for each item in JsonArray, add to Java ArrayList
for (int i = 0; i < array.size(); i++) {
stringList.add((array.get(i)).getAsString());
}
I fully agree with the JSON answers, but if this is a one-off hack, you could just do this:
String input = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
input = input.replace("[", "");
input = input.replace("]", "");
input = input.replace("\"", "");
String[] parts = input.split(",");
I make a number of assumptions here:
Assume no spaces before and after the delimiting [, ], ,
Assume no , and " character in the Strings you want to extract
input.substring(1, input.length() - 1).replaceAll("\\\"", "").split(",");
Or if you don't want to mess with regular expression (replaceAll function works with regular expression), then you can use replace method:
input.substring(1, input.length() - 1).replace("\"", "").split(",");
Due to the assumptions above, this answer is very brittle. Consider using JSON parser if the data is really JSON.
String str = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
String strArry[] = null;
if(str.trim().length() > 0){
str = str.substring(1 , str.length()-1).replaceAll("\\\"", "");
strArry = str.split(",");
}
If s is the input string, it can just be as simple as
String[] idArray = s.replaceAll("[\\[\\]\"]", "").split(",");
it would be more secure (because ',' may be a decimal separator) to split with ("\",\""), and not remove trailing " in replaceAll, here subtring do not parse all the string :
final String str = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
final String strArray[] = str.substring(2, str.length() - 2).split("\",\"");
final ArrayList<String> al = new ArrayList<String>();
for (final String string : strArray) {
al.add(string);
System.out.println(string);
}
System.out.println(al);
for (final String string : strArray) {
System.out.println(string);
}
Output :
4fd5f684815345
4fd6ef3e60a676854651
4fd83c33c19164512153
[4fd5f684815345, 4fd6ef3e60a676854651, 4fd83c33c19164512153]
Can I extract string from the phrase using split() function with subphrases as delimeters? For example I have a phrase "Mandatory string - Any string1 - Any string2". How can I extract "Any string1" with delimiters as "Mandatory string" and "[a-zA-Z]"
This is how I'm trying to extract:
String str="Mandatory string - Any string1 - Any string2";
String[] result= str.split("Mandatory\\string\\s-\\s|\\s-\\s[a-zA-Z]+");
Result of this code is
result = ["Mandatory string","ny string1","ny string2"]
But desired is:
result = ["Any string1"]
Could appreciate some help, thanks.
String[] result= str.split("Mandatory\\s(1)string\\s-\\s|\\s-\\s[a-zA-Z\\s(2)]+");
You just forgot an "s" in position(1)
and there should be a "\\s" in position(2)
try this line:
String[] result= str.split("Mandatory\\sstring\\s-\\s|\\s-\\s[a-zA-Z\\s]+");
First of all, there's a typo right here:
Mandatory\\string
This should probably read
Mandatory\\sstring
Anyway, I would either use " - " as the delimiter and get the second token:
str.split(" - ")[1] // TODO: prod version should do bounds checking etc
or use a different tool entirely, probably a regex match with the following regular expression:
"Mandatory string - (.*) - .*"
The parenthesised capture group will give you the string you're after.
Why not
String[] result = str.split(" - ");
return result.length < 2 ? "" : result[1];
If there is a definite format to your input string, just split it and then use the parts that are needed:
String[] resultArray = str.split(" - ");
String whatYouWant = resultArray[1];
I am getting this string from a program
[user1, user2]
I need it to be splitted as
String1 = user1
String2 = user2
You could do this to safely remove any brackets or spaces before splitting on commas:
String input = "[user1, user2]";
String[] strings = input.replaceAll("\\[|\\]| ", "").split(",");
// strings[0] will have "user1"
// strings[1] will have "user2"
Try,
String source = "[user1, user2]";
String data = source.substring( 1, source.length()-1 );
String[] split = data.split( "," );
for( String string : split ) {
System.out.println(string.trim());
}
This will do your job and you will receive an array of string.
String str = "[user1, user2]";
str = str.substring(1, str.length()-1);
System.out.println(str);
String[] str1 = str.split(",");
Try the String.split() methods.
From where you are getting this string.can you check the return type of the method.
i think the return type will be some array time and you are savings that return value in string . so it is appending [ ]. if it is not the case you case use any of the methods the users suggested in other answers.
From the input you are saying I think you are already getting an array, don't you?
String[] users = new String[]{"user1", "user2"};
System.out.println("str="+Arrays.toString(str));//this returns your output
Thus having this array you can get them using their index.
String user1 = users[0];
String user2 = users[1];
If you in fact are working with a String then proceed as, for example, #WhiteFang34 suggests (+1).