1

What I want to split is the following string:

<java><jquery><comments> 

I use the following split method like this:

 String s = "<java><jquery><comments>"; String[] arr = s.split("<|>"); for(String a: arr){ System.out.println(a); } 

The output is the following:

java jquery comments 

The problem is I don't want the blank line. The size of the array returned from splitting is 6. What I want it to be is 3 letter strings only.

Should I use regular expression to get all letters, or use split like above?

3 Answers 3

6

Change the split to s.split("[<>]+"). However, there still will be a "" at the beginning of the array, which is due to how split works.

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

2 Comments

If you're using [] you would want to remove the |. Otherwise you will split on the | character as well.
Thanks, missed that character. Tried to be too fast a gun in the answer:)
2

I think rather than String#split you should Pattern, Matcher and Matcher#find like this:

Pattern p = Pattern.compile("<([^>]+)>"); Matcher m = p.matcher("<java><jquery><comments>"); for (int i=0; m.find(); i++) System.out.printf("MATCHED[%d]: [%s]%n", i, m.group(1)); 

OUTPUT:

MATCHED[0]: [java] MATCHED[1]: [jquery] MATCHED[2]: [comments] 

Comments

0

You can also use a StringTokenizer object to split your string according to the correct pattern.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.