Java 使用替换替换字符串中的字母表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19886749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:02:55  来源:igfitidea点击:

Replace alphabet in a string using replace?

javareplace

提问by Arch1tect

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

我想知道是否可以string.replace()用来替换字符串中的所有字母?

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.

替代方案也受到欢迎,除非时间太长。

采纳答案by acdcjunior

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

JavaString#replaceAll将正则表达式字符串作为参数。话虽如此,[a-ZA-Z]匹配从ato z(小写)和Ato Z(大写)的任何字符,这似乎是您所需要的。

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

See demohere.

在这里查看演示

回答by Maroun

Use String#replaceAllthat takes a Regex:

使用String#replaceAll需要正则表达式

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

Note that String#replacetakes 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 replaceit with @. But if it's not a homework and you can use replaceAll, use it :)

请注意,String#replace将 String 作为参数而不是Regex。如果你还想使用它,你应该逐个字符地循环字符串并检查这个字符是否在 [az] 或 [AZ] 范围内,并将替换@. 但如果它不是家庭作业并且您可以使用replaceAll,请使用它:)

回答by Michael

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

您可以在这里阅读所有相关信息:http: //docs.oracle.com/javase/tutorial/essential/regex/index.html