TheOne
TheOne

Reputation: 11159

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

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"}

Upvotes: 34

Views: 30192

Answers (4)

newacct
newacct

Reputation: 122429

in Java 1.5+:

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

Upvotes: 67

TheOne
TheOne

Reputation: 11159

"hello|world".split("\\\\|"); --> {"hello", "world"}

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

Upvotes: -4

Hank Gay
Hank Gay

Reputation: 71939

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.

Upvotes: 1

Kevin
Kevin

Reputation: 30419

Escape it with \\:

"hello|world".split("\\|");

Upvotes: 57

Related Questions