Removing pipes from a string

T

Tom Gur

Hi,

I need to strip all of the pipe-characters of a string. normally I
would use something like:
str.replaceAll("the-char-i-want-to-replace", "");
But from some reason: str.replaceAll("|", "") do not alter the string.
currently I've wrote something like that:

private static String strip_for_validation(String str) {
return str.lastIndexOf('|') == -1 ? str.replaceAll(" ", "") :
strip_for_validation(str.substring(0,str.lastIndexOf('|')) +
str.substring(str.lastIndexOf('|')+1));
}

But is there any alteration I can make in order to use the much more
readable replaceAll method ?
 
R

Robert Klemme

I need to strip all of the pipe-characters of a string. normally I
would use something like:
str.replaceAll("the-char-i-want-to-replace", "");
But from some reason: str.replaceAll("|", "") do not alter the string.

Strings are immutable so no method will alter the string.

Second, I suggest you read the docs at

http://java.sun.com/j2se/1.5.0/docs...eplaceAll(java.lang.String, java.lang.String)

The first string is a regexp and as it happens, a pipe symbol is a meta
character. So you need to escape it.
currently I've wrote something like that:

private static String strip_for_validation(String str) {
return str.lastIndexOf('|') == -1 ? str.replaceAll(" ", "") :
strip_for_validation(str.substring(0,str.lastIndexOf('|')) +
str.substring(str.lastIndexOf('|')+1));
}

But is there any alteration I can make in order to use the much more
readable replaceAll method ?

See above.

Kind regards

robert
 
T

Tom Gur

Strings are immutable so no method will alter the string.

Second, I suggest you read the docs at

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#replace...)

The first string is a regexp and as it happens, a pipe symbol is a meta
character. So you need to escape it.




See above.

Kind regards

robert

Thanks, found it.
Since Java doesn't accept "\|", you can just type "\\|" so the regular
expression will read the pipe literally.
So, str.replaceAll("\\|", "") works fine.
 
T

Tom Gur

actually replace() receives 2 chars, not strings - so str.replace("|",
"") is illegal.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,056
Members
48,769
Latest member
Clifft

Latest Threads

Top