split string into array and add the delimiter to the array - java

i have an String and i need to split this String to array
My String is for example "-2x+3"
i split it with this code
public static String[] splitAnswer(String answerInput){
answerInput = answerInput.trim();
String[] token = answerInput.split("[\\+\\-\\*\\\\\\/]");
return token;
}
but i need the minus sign with 2x i.e. (-2x) and my array output will be {"-2x","3"}
the important thing i need the minus with the number after

You can use following regex:
String[] token = answerInput.split("[+*/]|(?=-)")
So, this splits on all the operators, except -. For - operator, it splits on empty string before the - operator. BTW, you don't need to escape anything inside the character class.
For -2x + 3, the split positions are:
|-2x+3 ( `|` is empty space)
^ ^

Related

How to remove everything apart from math signs java regex

I have a string which is a maths sum. e.g. 3+5*5/2 etc
I want to get one string array that contains the numbers and another array that contains the operations.
I have get the numbers by itself but I can't get the operations.
This is what I have so far:
String extractingIntegers = "4+5*9/8-6";
String[] operationsInStringformat = extractingIntegers.split("[^0-9]");
String[] numbersInStringformat = extractingIntegers.split("\\D");
The \\D works but not the [^0-9]
The opposite of \D is \d
String extractingIntegers = "4+5*9/8-6";
String[] operationsInStringformat = extractingIntegers.split("\\d");
String[] numbersInStringformat = extractingIntegers.split("\\D");
Just remove the ^ in the below line
String[] operationsInStringformat = extractingIntegers.split("[0-9]+");
Also include + to handle numbers with more than 1 digit.

how to remove multiple token from string array in java by split along with [ ]

how to remove multiple token from string array in java by split along with [ ]
String Order_Menu_Name= [pohe-7, puri-3];
String [] s2=Order_Menu_Name.split("-|,");
int j = 0;
//out.println("s2.length "+s2.length);
while(j<s2.length){ }
and expected output should be each value separate.
e,g pohe 7 puri 3
Your question is not clear. Assuming that your string contains "pohe-7, puri-3" you can split them using a separator such as "," or "-" or whitespace. See below.
String Order_Menu_Name= "[pohe-7, puri-3]";
To remove "[" and "]" from the above String. you can use Java's replace method as follow:
Order_Menu_Name = Order_Menu_Name.replace("[", "");
Order_Menu_Name = Order_Menu_Name.replace("]", "");
You can replace the above two lines with one using regex expression that matches [....] if you wish to.
After you removed the above characters then you can split your string as follow.
String[] chunks = Order_Menu_Name.split(",");
i = 0;
while(chunks.length) {
System.out.println(chunks[i]);
i++;
}
You can pass one or two params to the Java split() method, one being the regex expression that defines the pattern to be found and the second argument is limit, specifying how many chunks to return, see below:
public String[] split(String regex, int limit)
or
public String[] split(String regex)
For example
String Str = new String("Welcome-to-Stackoverflow.com");
for (String retval: Str.split("-", 3)){
System.out.println(retval);
}
When splitting the above Str using seperator "-" you should get 3 chunks of strings as follow:
Welcome
to
Stackoverflow.com
If you pass the split function a limit of 2 instead of three then you get the following:
Welcome
to-Stackoverflow.com
Notice above "to-Stckoverflow.com" is returned as is because we limited the chunks to 2.

Java Regex in round brackets

I am trying to parse an input string like this
String input = "((1,2,3),(3,4,5),(2,3,4),...)"
with the aim of getting an array of String where each element is an inner set of integers i.e.
array[0] = (1,2,3)
array[1] = (3,4,5)
etc.
To this end I am first of all getting the inner sequence with this regex:
String inner = input.replaceAll("\\((.*)\\)","$1");
and it works. Now I'd like to get the sets and I am trying this
String sets = inner.replaceAll("((\\((.*)\\),?)+","$1")
But I can't get the result I expected. What am I doing wrong?
Don't use replaceAll to remove the parentheses at the ends. Rather use String#substring(). And then to get the individual elements, again rather than using replaceAll, you should use String#split().
String input = "((1,2,3),(3,4,5),(2,3,4))";
input = input.substring(1, input.length() - 1);
// split on commas followed by "(" and preceded by ")"
String[] array = input.split("(?<=\\)),(?=\\()");
System.out.println(Arrays.toString(array));

String.split(String pattern) Java method is not working as intended

I'm using String.split() to divide some Strings as IPs but its returning an empty array, so I fixed my problem using String.substring(), but I'm wondering why is not working as intended, my code is:
// filtrarIPs("196.168.0.1 127.0.0.1 255.23.44.1 100.168.100.1 90.168.0.1","168");
public static String filtrarIPs(String ips, String filtro) {
String resultado = "";
String[] lista = ips.split(" ");
for (int c = 0; c < lista.length; c++) {
String[] ipCorta = lista[c].split("."); // Returns an empty array
if (ipCorta[1].compareTo(filtro) == 0) {
resultado += lista[c] + " ";
}
}
return resultado.trim();
}
It should return an String[] as {"196"."168"."0"."1"}....
split works with regular expressions. '.' in regular expression notation is a single character. To use split to split on an actual dot you must escape it like this: split("\\.").
Use
String[] ipCorta = lista[c].split("\\.");
in regular expressions the . matches almost any character.
If you want to match the dot you have to escape it \\..
Your statement
lista[c].split(".")
will split the first String "196.168.0.1" by any (.) character, because String.split takes a regular expression as argument.
However, the point, why you are getting an empty array is, that split will also remove all trailing empty Strings in the result.
For example, consider the following statement:
String[] tiles = "aaa".split("a");
This will split the String into three empty values like [ , , ]. Because of the fact, that the trailing empty values will be removed, the array will remain empty [].
If you have the following statement:
String[] tiles = "aaab".split("a");
it will split the String into three empty values and one filled value b like [ , , , "b"]
Since there are no trailing empty values, the result remains with these four values.
To get rid of the fact, that you don't want to split on every character, you have to escape the regular expression like this:
lista[c].split("\\.")
String.split() takes a regular expression as parameter, so you have to escape the period (which matches on anything). So use split("\\.") instead.
THis may help you:
public static void main(String[] args){
String ips = "196.168.0.1 127.0.0.1 255.23.44.1 100.168.100.1 90.168.0.1";
String[] lista = ips.split(" ");
for(String s: lista){
for(String s2: s.split("\\."))
System.out.println(s2);
}
}

having trouble with arrays and maybe split

String realstring = "&&&.&&&&";
Double value = 555.55555;
String[] arraystring = realstring.split(".");
String stringvalue = String.valueof(value);
String [] valuearrayed = stringvalue.split(".");
System.out.println(arraystring[0]);
Sorry if it looks bad. Rewrote on my phone. I keep getting ArrayIndexOutOfBoundsException: 0 at the System.out.println. I have looked and can't figure it out. Thanks for the help.
split() takes a regexp as argument, not a literal string. You have to escape the dot:
string.split("\\.");
or
string.split(Pattern.quote("."));
Or you could also simply use indexOf('.') and substring() to get the two parts of your string.
And if the goal is to get the integer part of a double, you could also simply use
long truncated = (long) doubleValue;
split uses regex as parameter and in regex . means "any character except line separators", so you could expect that "a.bc".split(".") would create array of empty strings like ["","","","",""]. Only reason it is not happening is because (from split javadoc)
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 because all strings are empty you get empty array (and that is because you see ArrayIndexOutOfBoundsException).
To turn off removal mechanism you would have to use split(regex, limit) version with negative limit.
To split on . literal you need to escape it with \. (which in Java needs to be written as "\\." because \ is also Strings metacharacter) or [.] or other regex mechanism.
Dot (.) is a special character so you need to escape it.
String realstring = "&&&.&&&&";
String[] partsOfString = realstring.split("\\.");
String part1 = partsOfString[0];
String part2 = partsOfString[1];
System.out.println(part1);
this will print expected result of
&&&
Its also handy to test if given string contains this character. You can do this by doing :
if (string.contains(".")) {
// Split it.
} else {
throw new IllegalArgumentException("String " + string + " does not contain .");
}

Categories