• Post Reply Bookmark Topic Watch Topic
  • New Topic

regex problem  RSS feed

 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have this fragment of the code:
...
String SEP=";\\|,";
String q="2000|3000|1000";
String[] sp=q.split(SEP);
System.out.println(sp.length);

I expected to get a '3' as result. But I am getting '1'.
I wanted to split 'q' on '|'.
What am I doing wrong. I tried :
SEP=";|," and SEP=";\\\\|," with the same result
Tnx,
Haris
 
Haris Karameh
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
never mind, figured it out:
String SEP=";|\\||,";
[ October 28, 2008: Message edited by: Haris Karameh ]
 
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you want to split on the | (vertical bar)



or split on the vertical bar, and on the comma, and on the semicolon?
(which don't happen to be in your source string)
 
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Haris Karameh:
never mind, figured it out:
String SEP=";|\\||,";

[ October 28, 2008: Message edited by: Haris Karameh ]


For multiple single characters, use a character class.
Note that the pipe character | does not have any special meaning inside a character class, so it doesn't need to be quoted with a (pair of) backslash(es) \\
 
Haris Karameh
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tnx Darryl,
that is what I was looking for. I do not use regex frequently .
Your solution is more elegant.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!