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
Replace alphabet in a string using replace?
提问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#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.
JavaString#replaceAll
将正则表达式字符串作为参数。话虽如此,[a-ZA-Z]
匹配从a
to z
(小写)和A
to Z
(大写)的任何字符,这似乎是您所需要的。
String sentence = "hello world! 722";
String str = sentence.replaceAll("[a-zA-Z]", "@");
System.out.println(str); // "@@@@@ @@@@@! 722"
See demohere.
回答by Maroun
Use String#replaceAll
that takes a Regex:
使用String#replaceAll
需要正则表达式:
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 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