使用replace替换字符串中的字母? [英] Replace alphabet in a string using replace?

查看:446
本文介绍了使用replace替换字符串中的字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我是否可以使用 string.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.

推荐答案

Java的 String#replaceAll 将正则表达式字符串作为参数。据说, [a-ZA-Z] 匹配来自 a 的任何字符到 z (小写)和 A Z (大写),这似乎是你的需要。

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"

参见 演示此处

这篇关于使用replace替换字符串中的字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆