Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

split string

 
dale con
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello

I'm trying to split a string (delimited with a pipe)

String s = "this|is|an|example";
String [] results = s.split("|");

String a = results[0]; // here io expect to get 'this'
String b = results[1]; // here io expect to get 'is'

But i'm not gettiong what i expect to get

Can anyone tell mewhere i'm going wrong
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The argument to split() is a regular expression, not just a plain old string. "|" is a special character in Java regular expressions; it represents "or", as in "this or that". Just an "|" alone ought to be an error, I'd think, but apparently it isn't; it seems to mean "nothing or nothing" in this context, so you're getting your string split at every character.

So, how to do this right? Escape the | with a backslash. You also have to protect the backslash with another backlash so that the Java compiler leaves it alone. So altogether, you want to use split("\\|") . This will work as you expect.
 
dale con
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cheers

Forgot about ecasping the pipe
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic