0

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]
0

3 Answers 3

1

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]
Sign up to request clarification or add additional context in comments.

4 Comments

Arrays.stream(str.split("\\]\\s*")).map(x -> String.format("%s]", x)).forEach(System.out::println);
@ElliottFrisch - Yes, that can be another way.
Well it's really the same way as this (slightly simpler regex, with different trade-offs). Which is why I left it as a comment.
@ElliottFrisch - Thanks for this addition. When a genius like you answers or comments, it helps many!
1

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());

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.