Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

java - Removing certain characters from a string

I am thinking about using String.replaceAll() to remove certain characters in my string. It is unclear which characters are going to be removed (i.e. which characters I want to remove), but I would assume that any character is valid (like [a-zA-Z] and things like $%!, etc).

I came across http://www.java-tips.org/java-se-tips/java.lang/strip-certain-characters-from-a-string.html but surely there is a better way than iterating over each character...

Any thoughts on this?

Thanks

EXAMPLE:

Just to clarify, I will have strings of varying lengths. I want to strip characters from it, the exact ones to be determined at runtime, and return the resulting string.

Taking the paragraph above and allowing me to strip out the ",.", I would return the string:

Just to clarify I will have strings of varying lengths I want to strip characters from it the exact ones to be determined at runtime and return the resulting string

As an aside, I know that replaceAll() uses regular expressions, so if I wanted to strip out the characters "$,.", I would need to escape them too, right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You might want to start by specifying which character you WANT to keep, try something like:

"mystring".replaceAll("[^a-zA-Z]", "")?

To only keep letters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...