简体   繁体   English

用Java中的字符串“ blank”替换多个连续出现的下划线字符“ _”

[英]Replace more than one continuous occurrence of underscore character “_” with the string “blank” in java

I need to replace more than one continuous repetition of character "_" in any string with the word "blank" such that This_is a test ___ becomes This_is a test blank . 我需要用单词“ blank”替换任何字符串中多个字符“ _”的连续重复,以使This_is test ____成为This_is test blank If there is only one "_" character, it should not be replaced. 如果只有一个“ _”字符,则不应替换。

Multiple consecutive underscores need to be replaced by blank so that the word blank will be uttered when the string is read for text to speech in android. 需要将多个连续的下划线替换为空格,以便在读取字符串以在android中进行文字转语音时说出空白一词。

You can do this with a Regular Expression . 您可以使用正则表达式执行此操作。 Luckily, there is a method on String called replaceAll() that takes a Regular Expression: 幸运的是,在String上有一个名为replaceAll()的方法,该方法带有一个正则表达式:

final String input = "This_is a test ___";
final String output = input.replaceAll("_{2,}", "blank");
System.out.println(output);  // Prints "This_is a test blank"

What the expression there means is: "find at least 2 consecutive occurrences of underscore". 该表达式的含义是:“查找至少2个连续的下划线”。

You can use the replaceAll() method: 您可以使用replaceAll()方法:

String str = "This_ is a ____";
str = str.replaceAll("[_]{2,}", "blank");

Output: 输出:

This_ is a blank

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM