Reputation: 11
I have following string:
+420354599951 [table] +420354599969 [table] +420354599969 [fax] +420354599969 [mobile]
I need to seperate it everytime when [table], [fax] or [mobile] occur. So I need to create from this string 4 different strings:
+420354599951 [table]
+420354599969 [table]
+420354599969 [fax]
+420354599969 [mobile]
Upvotes: 0
Views: 93
Reputation:
You can use regular expressions for this purpose:
String str = "+420354599951 [table] +420354599969 [table] " +
"+420354599969 [fax] +420354599969 [mobile]";
String[] arr = Arrays.stream(str
// replace sequences (0 and more)
// of whitespace characters
// after closing square brackets
// with delimiter characters
.replaceAll("(])(\\s*)", "$1::::")
// split this string by
// delimiter characters
.split("::::", 0))
.toArray(String[]::new);
// output in a column
Arrays.stream(arr).forEach(System.out::println);
Output:
+420354599951 [table]
+420354599969 [table]
+420354599969 [fax]
+420354599969 [mobile]
See also: How to split a string delimited on if substring can be casted as an int
Upvotes: 0
Reputation: 11
Taking @ElliottFrisch's example one small step further, you can save the Strings in a List
using the Java Stream API Collectors as follows:
List<String> numbers = Arrays.stream(str.split("\\]\\s*"))
.map(x -> String.format("%s]", x))
.collect(Collectors.toList());
Upvotes: 1
Reputation: 79480
Split the string using the regex, (?=\\+)
where ?=
specifies positive lookahead assertion.
Demo:
class Main {
public static void main(String[] args) {
String str = "+420354599951 [table] +420354599969 [table] +420354599969 [fax] +420354599969 [mobile]";
String[] parts = str.split("(?=\\+)");
// Display each element from the array
for (String part : parts) {
System.out.println(part);
}
}
}
Output:
+420354599951 [table]
+420354599969 [table]
+420354599969 [fax]
+420354599969 [mobile]
Upvotes: 1