Replace alphabet in a string using replace?

18,649

Solution 1

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.

Solution 2

Use String#replaceAll that takes a Regex:

str = str.replaceAll("[a-zA-Z]", "@");

Note that String#replace takes a String as argument and not a Regex. If you still want to use it, you should loop on the String char-by-char and check whether this char is in the range [a-z] or [A-Z] and replace it with @. But if it's not a homework and you can use replaceAll, use it :)

Solution 3

You can use the following (regular expression):

    String test = "hello world! 722";
    System.out.println(test);
    String testNew = test.replaceAll("(\\p{Alpha})", "@");
    System.out.println(testNew);

You can read all about it in here: http://docs.oracle.com/javase/tutorial/essential/regex/index.html

Share:
18,649
Arch1tect
Author by

Arch1tect

sup

Updated on June 07, 2022

Comments

  • Arch1tect
    Arch1tect almost 2 years

    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.

  • acdcjunior
    acdcjunior over 10 years
    More about the [a-zA-Z] regex here: regular-expressions.info/charclass.html
  • Maroun
    Maroun over 10 years
    @Arch1tect That's not weird, my mistake :))
  • Mike Housky
    Mike Housky over 10 years
    I'd say this is more of a primary solution, with the a-zA-Z solutions being alternatives for pretty much English locales only. (Hawaiian works, too. :^)