replace period using String.replaceAll()

S

sfu

Hi

i'm trying to remove all occurances of . from a string

test = test.replaceAll(".","");

and

int fs = 46;
Character fullstop = new Character((char) fs);
test = test.replaceAll(fullstop.toString(),"");

both dont work, any ideas on how to get it to work?

cheers
 
S

secret

It appears that your problem is that the period has a defined meaning within
regular expression. This is not replacing a substring in the way you
imagine.

Try putting two backslashes in front of the period. One backslash is needed
to escape the char in the regular expression. The other is needed to escape
the first backslash in Java.

test = test.replaceAll("\\.","");
 
S

secret

I just reread my post and decided it was quite unitelligible (though the
code works).

The essence of your problem is that the method replaceAll in String does not
replace a substring with the replacement string the way you might
intuitively imagine. Chech the API and you'll see that the first argument
is a regular expression, not a substring of the target.

good luck

alan
 
C

Chris Smith

secret said:
I just reread my post and decided it was quite unitelligible (though the
code works).

The essence of your problem is that the method replaceAll in String does not
replace a substring with the replacement string the way you might
intuitively imagine. Chech the API and you'll see that the first argument
is a regular expression, not a substring of the target.


The part that's far less clear from the documentation is that the second
parameter isn't just a String either; it's a pseudo-regexp where most
special characters don't work, but subexpression references do. That
means, essentially, that you have to be sure to properly escape BOTH
parameters to this method (and in consequence, the method is practically
useless unless both parameter values are known when the code is
written).

In the OP's case, that's not a problem, though. Just a gotcha to look
out for.

--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
S

sfu

secret said:
It appears that your problem is that the period has a defined meaning within
regular expression. This is not replacing a substring in the way you
imagine.

Try putting two backslashes in front of the period. One backslash is needed
to escape the char in the regular expression. The other is needed to escape
the first backslash in Java.

test = test.replaceAll("\\.","");

cheers mate!
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top