2

Im trying to split a sting on multiple or single occurences of "O" and all other characters will be dots. I'm wondering why this produces en empty string first.

String row = ".....O.O.O"
String[] arr = row.split("\\.+");

This produces produces:

["", "O", "O", "O"]
3
  • do strip and then split Commented May 24, 2018 at 9:20
  • row.replaceFirst("\\.+").split("\\.+") Commented May 24, 2018 at 9:26
  • replaceFirst method need two arguments.. it should be row.replaceFirst("\\.+","").split("\\.+") Commented May 24, 2018 at 9:28

3 Answers 3

2

You just need to make sure that any trailing or leading dots are removed.

So one solution is:

row.replaceAll("^\\.+|\\.+$", "").split("\\.+");
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, you don't get the same issue with trailing dots. Presumably becuase the final delimiter gets treated as marking the end of the fields, rather than the start of another field. Without the + you'd get empty fields at the end, but with it, you only need to strip leading delimiters.
1

For this pattern you can use replaceFirstMethod() and then split by dot

String[] arr = row.replaceFirst("\\.+","").split("\\.");

Output will be

["O","O","O"]

1 Comment

This merges the first two occurences if the string starts with an "O".
1

The "+" character is removing multiple instances of the seperator, so what your split is essentially doing is splitting the following string on "."

.0.0.0.

This, of course, means that your first field is empty. Hence the result you get.

To avoid this, strip all leading separators from the string before splitting it. Rather than type some examples on how to do this, here's a thread with a few suggestions.

Java - Trim leading or trailing characters from a string?

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.