Java regex convert - java

How convert String s = "[[1, value one, v3], [2, value two, v3]]" to
"[[\"1\",\"value one\",\"v3\"],[\"2\",\"value two\",\"v3\"]]" for parsing since
Type typeToken = new TypeToken<ArrayList<ArrayList<String>>>() {}.getType();
List<List<Object>> list = new Gson().fromJson(s, typeToken);
throws com.google.gson.stream.MalformedJsonException: Unterminated array at...

This could work:
String s = "[[1, value one, v3], [2, value two, v3]]"
.replaceAll("([\\[,]\\s*)([^\\[\\]\\\"]+?)(\\s*[\\],])", "$1\"$2\"$3")
.replaceAll("([\\[,]\\s*)([^\\[\\]\\\"]+?)(\\s*[\\],])", "$1\"$2\"$3");
For some reason I could not get it to work from the first run - you have to run the replacement twice. Sorry for that.

This is the regex (without Java escaping of \):
\[([\d]+),\s*([\w\s]+),\s*([\w]+)\]
Details:
\[: matches [
([\d]+): first value specifically one or more digits
\s?([\w\s]+): second value a "string with spaces" \s* check if a spaces are present (zero or more).
\s?([\w]+): third value a string with no spaces, also here \s? is checking if a spaces are present.
\]: matches ]
Java test:
public class Main {
public static void main(String[] args) {
String s = "[[1, value one, v3], [2, value two, v3]]";
System.out.println("input: " + s);
String o = s.replaceAll("\\[([\\d]+),\\s*([\\w\\s]+),\\s*([\\w]+)\\]", "[\"$1\",\"$2\",\"$3\"]");
System.out.println("output: " + o);
}
}
Result:
input: [[1, value one, v3], [2, value two, v3]]
output: [["1","value one","v3"], ["2","value two","v3"]]

Related

Split comma-separated string but ignore comma followed by a space

public static void main(String[] args) {
String title = "Today, and tomorrow,2,1,2,5,0";
String[] titleSep = title.split(",");
System.out.println(Arrays.toString(titleSep));
System.out.println(titleSep[0]);
System.out.println(titleSep[1]);
}
output:
[Today, and tomorrow, 2, 1, 2, 5, 0]
Today
(space) and tomorrow
I want to treat "Today, and tomorrow" as a phrase representing the first index value of titleSep (do not want to separate at comma it contains).
What is the split method argument that would split the string only at commas NOT followed by a space?
(Java 8)
Use a negative look ahead:
String[] titleSep = title.split(",(?! )");
The regex (?! ) means "the input following the current position is not a space".
FYI a negative look ahead has the form (?!<some regex>) and a positive look ahead has the form (?=<some regex>)
The argument to the split function is a regex, so we can use a negative lookahead to split by comma-not-followed-by-space:
String title = "Today, and tomorrow,2,1,2,5,0";
String[] titleSep = title.split(",(?! )"); // comma not followed by space
System.out.println(Arrays.toString(titleSep));
System.out.println(titleSep[0]);
System.out.println(titleSep[1]);
The output is:
[Today, and tomorrow, 2, 1, 2, 5, 0]
Today, and tomorrow
2

Split string in latest occurrence of substring

I need help to split string when substring is found, only on latest occurrence
Substring to search(example):123
String: 123hello123boy123guy123girl
Res: 123hello123boy123guy (result on split[0])
Ex: hello123boy
Res:hello
I'm trying with this function, but this split only on first occource.
public static String[] getSplitArray(String toSplitString, String spltiChar) {
return toSplitString.split("(?<=" + spltiChar + ")");
}
If you want to do it in single split(), this should work:
string.split("123((?!123).)*?$")
E.g.:
String s = "foo123bar123hhh123tillHere123Bang";
System.out.println(s.split("123((?!123).)*?$")[0]);
Outputs:
foo123bar123hhh123tillHere
Another approach would be, just split("123") then join the elements you required by 123 as delimiter.
Improvement on Kent's answer: this will actually give you a split array rather than a single-element array with the first part of your String:
String[] text = {
"123hello123boy123guy123girl", // 123hello123boy123guy
"hello123boy"// hello
};
for (String s: text) {
System.out.println(
Arrays.toString(
s.split("123(?=((?!123).)*?$)")
)
);
}
Output
[123hello123boy123guy, girl]
[hello, boy]
You don't need a regex for that, you can simply use String#lastIndexOf:
-> String s = "123hello123boy123guy123girl"
-> s.substring(0, s.lastIndexOf("123"));
| Expression value is: "123hello123boy123guy"
-> s.substring(s.lastIndexOf("123"));
| Expression value is: "123girl"

Java array, keep getting [I#6d06d69c [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
I am using trying to use the toString(int[]) method, but I think I am doing it wrong:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#toString(int[])
My code:
int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;
System.out.println(array.toString());
The output is:
[I#23fc4bec
Also I tried printing like this, but:
System.out.println(new String().toString(array)); // **error on next line**
The method toString() in the type String is not applicable for the arguments (int[])
I took this code out of bigger and more complex code, but I can add it if needed. But this should give general information.
I am looking for output, like in Oracle's documentation:
The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space).
What you want is the Arrays.toString(int[]) method:
import java.util.Arrays;
int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;
..
System.out.println(Arrays.toString(array));
There is a static Arrays.toString helper method for every different primitive java type; the one for int[] says this:
public static String toString(int[] a)
Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(int). Returns "null" if a is null.
System.out.println(array.toString());
should be:
System.out.println(Arrays.toString(array));
Very much agreed with #Patrik M, but the thing with Arrays.toString is that it includes "[" and "]" and "," in the output. So I'll simply use a regex to remove them from outout like this
String strOfInts = Arrays.toString(intArray).replaceAll("\\[|\\]|,|\\s", "");
and now you have a String which can be parsed back to java.lang.Number, for example,
long veryLongNumber = Long.parseLong(intStr);
Or you can use the java 8 streams, if you hate regex,
String strOfInts = Arrays
.stream(intArray)
.mapToObj(String::valueOf)
.reduce((a, b) -> a.concat(",").concat(b))
.get();
You can use java.util.Arrays:
String res = Arrays.toString(array);
System.out.println(res);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The toString method on an array only prints out the memory address, which you are getting.
You have to loop though the array and print out each item by itself
for(int i : array) {
System.println(i);
}
Using the utility I describe here, you can have a more control over the string representation you get for your array.
String[] s = { "hello", "world" };
RichIterable<String> r = RichIterable.from(s);
r.mkString(); // gives "hello, world"
r.mkString(" | "); // gives "hello | world"
r.mkString("< ", ", ", " >"); // gives "< hello, world >"
This function returns a array of int in the string form like "6097321041141011026"
private String IntArrayToString(byte[] array) {
String strRet="";
for(int i : array) {
strRet+=Integer.toString(i);
}
return strRet;
}
Here's an example of going from a list of strings, to a single string, back to a list of strings.
Compiling:
$ javac test.java
$ java test
Running:
Initial list:
"abc"
"def"
"ghi"
"jkl"
"mno"
As single string:
"[abc, def, ghi, jkl, mno]"
Reconstituted list:
"abc"
"def"
"ghi"
"jkl"
"mno"
Source code:
import java.util.*;
public class test {
public static void main(String[] args) {
List<String> listOfStrings= new ArrayList<>();
listOfStrings.add("abc");
listOfStrings.add("def");
listOfStrings.add("ghi");
listOfStrings.add("jkl");
listOfStrings.add("mno");
show("\nInitial list:", listOfStrings);
String singleString = listOfStrings.toString();
show("As single string:", singleString);
List<String> reconstitutedList = Arrays.asList(
singleString.substring(0, singleString.length() - 1)
.substring(1).split("[\\s,]+"));
show("Reconstituted list:", reconstitutedList);
}
public static void show(String title, Object operand) {
System.out.println(title + "\n");
if (operand instanceof String) {
System.out.println(" \"" + operand + "\"");
} else {
for (String string : (List<String>)operand)
System.out.println(" \"" + string + "\"");
}
System.out.println("\n");
}
}

split string only on first instance - java

I want to split a string by '=' charecter. But I want it to split on first instance only. How can I do that ? Here is a JavaScript example for '_' char but it doesn't work for me
split string only on first instance of specified character
Example :
apple=fruit table price=5
When I try String.split('='); it gives
[apple],[fruit table price],[5]
But I need
[apple],[fruit table price=5]
Thanks
string.split("=", limit=2);
As String.split(java.lang.String regex, int limit) explains:
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
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.
The string boo:and:foo, for example, yields the following results with these parameters:
Regex Limit Result
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }
Yes you can, just pass the integer param to the split method
String stSplit = "apple=fruit table price=5"
stSplit.split("=", 2);
Here is a java doc reference : String#split(java.lang.String, int)
As many other answers suggest the limit approach, This can be another way
You can use the indexOf method on String which will returns the first Occurance of the given character, Using that index you can get the desired output
String target = "apple=fruit table price=5" ;
int x= target.indexOf("=");
System.out.println(target.substring(x+1));
String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex. But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.
This works:
public class Split
{
public static void main(String...args)
{
String a = "%abcdef&Ghijk%xyz";
String b[] = a.split("%", 2);
System.out.println("Value = "+b[1]);
}
}
String[] func(String apple){
String[] tmp = new String[2];
for(int i=0;i<apple.length;i++){
if(apple.charAt(i)=='='){
tmp[0]=apple.substring(0,i);
tmp[1]=apple.substring(i+1,apple.length);
break;
}
}
return tmp;
}
//returns string_ARRAY_!
i like writing own methods :)

java split () method

I've got a string '123' (yes, it's a string in my program). Could anyone explain, when I use this method:
String[] str1Array = str2.split(" ");
Why I got str1Array[0]='123' rather than str1Array[0]=1?
str2 does not contain any spaces, therefore split copies the entire contents of str2 to the first index of str1Array.
You would have to do:
String str2 = "1 2 3";
String[] str1Array = str2.split(" ");
Alternatively, to find every character in str2 you could do:
for (char ch : str2.toCharArray()){
System.out.println(ch);
}
You could also assign it to the array in the loop.
str2.split("") ;
Try this:to split each character in a string .
Output:
[, 1, 2, 3]
but it will return an empty first value.
str2.split("(?!^)");
Output :
[1, 2, 3]
the regular expression that you pass to the split() should have a match in the string so that it will split the string in places where there is a match found in the string. Here you are passing " " which is not found in '123' hence there is no split happening.
Because there's no space in your String.
If you want single chars, try char[] characters = str2.toCharArray()
Simple...You are trying to split string by space and in your string "123", there is no space
This is because the split() method literally splits the string based on the characters given as a parameter.
We remove the splitting characters and form a new String every time we find the splitting characters.
String[] strs = "123".split(" ");
The String "123" does not have the character " " (space) and therefore cannot be split apart. So returned is just a single item in the array - { "123" }.
To do the "Split" you must use a delimiter, in this case insert a "," between each number
public static void main(String[] args) {
String[] list = "123456".replaceAll("(\\d)", ",$1").substring(1)
.split(",");
for (String string : list) {
System.out.println(string);
}
}
Try this:
String str = "123";
String res = str.split("");
will return the following result:
1,2,3

Categories

Resources