1

I have an interesting string I want to properly break up into a string array. This string is as follows.

String test="?[32,120],x1y1,[object pieceP1],null]";

Now I have this regular expression to attack this.

String delims = "[?,\\[\\]]";

Now the results of splitting it using this code

String[] tokens = mapString.split(delims);

yields this result

-->
-->
32
120
-->
x1y1
-->
object pieceP1
-->
null

where the arrows are the empty lines.

How can I modify this regular expression so that there are no empty lines?

Thank you greatly in advance.

~ Selcuk

3 Answers 3

2

String delims = "[?,\\[\\]]+"; // []+

see the Greedy quantifiers part in Summary of regular-expression constructs of Pattern

but the leading empty element is still there.

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

Comments

2

You could use Google Guava's Splitter class to facilitate that: http://guava-libraries.googlecode.com/svn/tags/release09/javadoc/com/google/common/base/Splitter.html

Splitter.omitEmptyStrings() should do the work.

Comments

1

Try this

public class Regex 
{
    public static void main(String[] args) 
    {
        String []split = "?[32,120],x1y1,[object pieceP1],null]".split("([?,\\[\\]])+");
        for (int i = 0; i < split.length; i++) {
            System.out.println("'"+split[i]+"'");
        }
    }
}

If your test string starts with a delimiter then the index 0 of the array will always be an empty string. You can put a check for it like this if(split[0].length == 0) continue;

>>Output

''
'32'
'120'
'x1y1'
'object pieceP1'
'null'

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.