tags:

views:

530

answers:

5

What is the proper way of inserting a pipe into a Java Pattern expression?

I actually want to use a pipe as a delimiter and not the or operator.

I.E:

"hello|world".split("|"); --> {"hello", "world"}
+1  A: 
"hello|world".split("\\\\|"); --> {"hello", "world"}

First set of "\\" only yields the \ as the delimiter. Therefore 2 sets are needed to escape the pipe.

Absolute0
right solution, wrong explanation. The regexp needed is \| (two characters) and if you want to put a backslash in the string in Java, you need to use a double backslash to tell Java the backslash isn't being used to escape the next character.
Jason S
shit stackoverflow escaped my slashes :(
Absolute0
That's what code sections are for :-)
Joey
Why don't you just delete this answer and accept Kevin's?
Alan Moore
Kevin's is wrong you need 4 slashes.
Absolute0
+8  A: 

Escape it with \\:

"hello|world".split("\\|");
Kevin
+1  A: 

I have this problem a lot (encoding a regex into a Java String), so I have bookmarked the regex tool at fileformat.info; it has a nifty function where it will show you the Java String representation of a regex after you test it.

Hank Gay
That's pretty cool!You could also simply play around with watch statements in the eclipse debug environment.
Absolute0
A: 

As already said by Kevin, you need to escape it.

Also if you're using Eclipse or you want to have a WYSIWYG editor for regexps in Java, visit myregexp.com from where you either get as Eclipse plugin or use as applet IMO the best Java regex util I've ever seen.

Esko
+2  A: 

in Java 1.5+:

"hello|world".split(Pattern.quote("|"));
newacct