3

My code looks like below,

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

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

Expected output :

testfile

testfile

Output received:

t 

e

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

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.