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

why the output is different from usual String.split()

 
charan sri
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.lang.*;
class StringSplit
{
public static void main(String[] args)
{
String str="sss|sss|ssssss|sssds|sssss";
String[] a= str.split("/|");
for(int i=0;i<a.length;i++)
{
System.out.println(i+"-->"+a[i]);
}
}
}
Can any one explain me why the above code is behaving differently?
If i give ',' in place of '|' the output is correct.
I dont undersatand why?

Thanks
Charan.
 
charan sri
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Administrators or moderators plz delete my previous topic.

Thanks,
Charan.
 
Todd Johnson
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not completely up to speed on regular expressions, but I believe the pipe (|) has the special meaning "OR" in a regular expression. So the following code...

String[] a = str.split("|");

Really doesn't make sense (it matches everything I'm guessing). So if we want to look for the literal character pipe (|) we need to escape it out like this...

String[] a = str.split("\\|");

This will give you the behaviour you are looking for.
 
Akshay Kiran
Ranch Hand
Posts: 220
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
exactly, you need to escape it twice because '|' is a Metacharacter while ',' is not and doesn't need to be escaped.
Also note however this intricacy

String s= "\\|";

does the same work as
String s= arg[0]
and arg[0]= "\|" at the command line or from a file.
 
charan sri
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks akshay and Johnson

Thanks,
Charan.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic