4

My code looks like below,

string filename  = '/*testfile /*testfile';

List<String> parts = filename.split('/*');

Expected output :

testfile

testfile

Output received:

t 

e

s
..
1
  • Are you trying to parse the comments? Because they should terminate with */ , not another /*. Also you ignore // style comments with this approach.
    – Adrian Larson
    Commented Dec 27, 2016 at 14:58

1 Answer 1

8

Split actually expects a regular expression, so your split string is interpreted as "split when there are zero or more / characters" ("*" means "zero or more").

To avoid this behavior, you have to "escape" the "*" character with a backslash, which itself needs to be escaped with a backslash:

List<String> parts = filename.split('/\\*');

Without that escape, it tries to split every character from every other character, with the slash ("/") being stripped out entirely.

If you look at the String methods, the documentation tells you this explicitly:

split(regExp)

Returns a list that contains each substring of the String that matches this pattern.

Signature

public String[] split(String regExp)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .