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
357 views
in Technique[技术] by (71.8m points)

java - How to remove invalid characters from a string?

I have no idea how to remove invalid characters from a string in Java. I'm trying to remove all the characters that are not numbers, letters, or ( ) [ ] . How can I do this?

Thanks

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
String foo = "this is a thing with & in it";
foo = foo.replaceAll("[^A-Za-z0-9()\[\]]", "");

Javadocs are your friend. Regular expressions are also your friend.

Edit:

That being siad, this is only for the Latin alphabet; you can adjust accordingly. \w can be used for a-zA-Z to denote a "word" character if that works for your case though it includes _.


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

...