java - 如何替换子串的每个索引

标签 java regex replace

String s = "Elephant";
String srep = (s.replaceAll(s.substring(4,6), "_" ));

System.out.println(srep);

所以我的代码输出 Elep_nt 但我希望它用下划线替换该子字符串的每个单独索引,以便输出 Elep__nt 有没有办法在一行中做到这一点?我必须使用循环吗?

最佳答案

你的问题是你一次匹配 "ha",因此它只被一个字符替换。 (另请注意,如果您有 "Elephantha",最后的 "ha" 也会被替换。)

你可以使用 lookbehind确定要替换的每个单个字符。因此,要“将位置 4 到 5 的字符替换,您可以使用:

String s = "Elephant";
String srep = s.replaceAll("(?<=^.{4,5}).", "_");

System.out.println(srep);

输出:

Elep__nt

关于java - 如何替换子串的每个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18747403/

相关文章:

regex - 警告 : nonstandard use of escape in a string literal

java - perl 和 java 正则表达式功能之间有什么区别?

mysql - 用 MySQL 替换 BLOB 文本中的单词

java - 这段代码的时间问题

java - Collection<Sub> 转换为 SuperCollection<Super>

arrays - Perl 数组 : Pattern matches then move to the another array

javascript - 在 Javascript 中用大写字母替换正则表达式捕获组

Python 从 DataFrame 字符串字段中去除所有空格

java - Fragment 和 ViewPager ClassCastException

java - 已创建配置单元表,但是映射任务失败,并带有异常