1

I am trying to split a string that has two numbers and possibly a letter that will look similar to:

(2,3) (2,6) p (8,5) p (5,6)

I am trying:

String inputTokens = input.split([(),\\s]);

but that leaves me with with a bunch of empty strings in the tokens array. How do I stop them from appearing in the first place?

For clarification: By empty string I mean a string containing nothing, not even a space

2 Answers 2

3

Add the "one or more times" greediness quantifier to your character class:

String[] inputTokens = input.split("[(),\\s]+");

This will result in one leading empty String, which is unavoidable when using the split() method and splitting away the immediate start of the String and otherwise no empty Strings.

Sign up to request clarification or add additional context in comments.

2 Comments

This worked really well, thanks! The only empty string left is in the 0th slot, is there an easy way to remove this?
Instead of splitting away unwanted characters do the opposite: write a regex for what you want to match, create a java.util.regex.Matcher and iterate over all the matches. See an example of how that works here: stackoverflow.com/a/42634031/1749753
1
String inputTokens[] = input.split("[(),\\s]+");

This will read the whitespace as part of the regex so there will be no empty entries in your array.

1 Comment

That hasn't really changed anything, I'm pretty sure it's seeing the ) ( between entries and putting empty strings between them

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.