I have to separate a string into an array that may contain empty spaces, for example,
|maria|joao|fernando||
but it is ignored when you have space at the end of the line
I am using this regex split("\\|")
It should be like it: maria,joao,fernando,null
but stays like this: maria,joao,fernando
You can use:
String str = "|maria|joao|fernando||";
String[] tokens = str.replaceAll("^[|]|[|]$", "").split("[|]", -1));
//=> [maria, joao, fernando, ""]
Steps:
Replace starting and ending | using replaceAll method to get maria|joao|fernando| as input to split.
Then split it using split method with 2nd parameter as -1 to return empty tokens as well.
You only need to add double backslashes to you split string
String s = "|maria|joao|fernando||";
String [] st =s.split("\\|");
for (String string : st) {
System.out.print(string+",");
}
Java 8 solution
List<String> params = Pattern
.compile("\\|")
.splitAsStream("|maria|joao|fernando||")
.filter(e -> e.trim().length() > 0) // Remove spaces only or empty strings
.collect(Collectors.toList());
Related
I have a list of titles that I want to save as a String:
- title1
- title2
- title|3
Now, I want to save this as a single line String delimited by |, which would mean it ends up like this: title1|title2|title|3.
But now, when I split the String:
String input = "title1|title2|title|3";
String[] splittedInput = input.split("\\|");
splittedInput will be the following array: {"title1", "title2", "title", "3"}.
Obviously, this is not what I want, I want the third entry of the array to be title|3.
Now my question: how do I correctly escape the | in the titles so that when I split the String I end up with the correct array of three titles, instead of 4?
#Gábor Bakos
Running this code snippet:
String input = "title1|title2|title\\|3";
String[] split = input.split("(?<!\\\\)\\|");
for (int i = 0; i < split.length; i++) {
split[i] = split[i].replace("\\\\(?=\\|)", "");
}
System.out.println(Arrays.toString(split));
I get this output: [title1, title2, title\|3]. What am I doing wrong?
You can use anything. For example with \:
"title1|title2|title\\|3".split("(?<!\\\\)\\|").map(_.replaceAll("\\\\(?=\\|)", "")) //Scala syntax
Resulting:
Array(title1, title2, title|3)
The final mapping is required to remove the escaping character too.
(?<!\\\\) is look behind, (?=\\|) is an extra look-ahead for the escaped |.
Well if you use a TSV format the chosen separator must never be left unescaped in the data.
You could simply escape your data (for ex, title1|title2|title\|3) and you would then split on (?<!\\)| (negative lookbehind).
In Java, it gives:
public static void main(String[] args) {
// prints out [title1, title2, title|3, title|4]
System.out.println(parsePipeSeparated("title1|title2|title\\|3|title\\|4"));
}
private static List<String> parsePipeSeparated(String input) {
return Stream.of(input.split("(?<!\\\\)\\|"))
.map(escapedText -> escapedText.replace("\\|", "|"))
.collect(Collectors.toList());
}
Use another separator, for instance "title1,title2,title|3", instead of "title1|title2|title|3". And then split(",")
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.
My problem is I have a string like this
String text="UWU/CST/13/0032 F"
I want this to split by / and white spaces and put into a array.So finally the array indexes should include following
UWU,
CST,
13,
0032,
F
text.split("[/ ]"), or text.split("[/ ]", -1) if you want trailing empty tokens to be returned.
Use the string.split(separator) method that takes a String (regex expression) as an argument. Here is the documentation. http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
If you have:
String text = "UWU/CST/13/0032 F";
You can separate it by the white space first, splitting it into an array of two Strings, and then split the first String in the array by "/".
String text = "UWU/CST/13/0032 F";
String[] array = text.split(" ");
String[] other = array[0].split("/");
for (String e : array) System.out.println(e);
for (String e : other) System.out.println(e);
This code outputs:
UWU/CST/13/0032
F
UWU
CST
13
0032
Regular expressions can be used in Java to split Strings using the String.split(String) method.
For you particular situation, you should split the string on the regular expression "(\s|/)". \s matches white space while / literally matches a forward slash.
The final code for this would be:
String[] splitString = text.split("(\\s|/)");
I have issues in using java string tokenizer:
String myString = "1||2||3|||4";
StringTokenizer stp = new StringTokenizer(myString, "||");
while (stp.hasMoreTokens()) {
System.out.println(stp.nextToken());
}
actual output : [1,2,3,4]
expected output : [1,2,3,'|4']
Could any one help me on the same
Try this..
String myString = "1||2||3|||4";
String[] s=myString.split("\\|\\|");
for (String string : s) {
System.err.println(string);
}
I think you cannot do anything because it's how StringTokenizer works (you can put returnDelims true and remove it manually but it's more hard than look sometimes)
String myString = "1||2||3|||4";
String[] tokens = myString.split("\\|\\|");
for(String token : tokens)
{
System.out.println(token);
}
You can use split which does what you want.
Output:
1
2
3
|4
It is recommended to use the split method of the String class for doing this since StringTokenizer matches the given string and split takes a regular expression. I would use this:
String[] splitStr = myString.split("[|]{2}");
This matches every time the regular expression [|] (a single pipe) is matched twice in a row.
You are maybe thinking of String.split, as this splits on a delimiter string.
A StringTokenizer takes the delimiter string and recognizes all characters in it as a delimiter. So in fact you redundantly specified the "|" character a second time.
Using the split function is what you maybe wanted:
System.out.println(Arrays.toString("1||2||3|||4".split("\\|\\|")));
This produces
[1, 2, 3, |4]
take a look this is an easy solution:
StringTokenizer stp = new StringTokenizer(myString, "|");
while (stp.hasMoreTokens()) {
System.out.println(stp.nextToken());
}
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);
}
}