Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace alphabet in a string using replace?

Tags:

java

replace

I'm wondering if I can use string.replace() to replace all alphabets in a string?

String sentence = "hello world! 722"
String str = sentence.replace("what to put here", "@");
//now str should be "@@@@@ @@@@@! 722"

In other words, how do I represent alphabetic characters?

Alternatives are welcomed too, unless too long.

like image 669
Arch1tect Avatar asked Nov 10 '13 05:11

Arch1tect


1 Answers

Java's String#replaceAll takes a regex string as argument. Tha being said, [a-ZA-Z] matches any char from a to z (lowercase) and A to Z (uppercase) and that seems to be what you need.

String sentence = "hello world! 722";
String str = sentence.replaceAll("[a-zA-Z]", "@");
System.out.println(str); // "@@@@@ @@@@@! 722"

See demo here.

like image 74
acdcjunior Avatar answered Sep 29 '22 07:09

acdcjunior