java - 替换字符串中特定位置的字符

标签 java regex string replace

我有以下字符串;

String s = "Hellow world,how are you?\"The other day, where where you?\"";

我想替换,,但只替换引号内的那个“The other day, where where you?”。

可以用正则表达式吗?

最佳答案

String s = "Hellow world,how are you?\"The other day, where where you?\"";
Pattern pattern = Pattern.compile("\"(.*?)\"");
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
    s = s.substring(0, matcher.start()) + matcher.group().replace(',','X') + 
            s.substring(matcher.end(), s.length());                                  
}

如果引号超过两个,则会将文本分为引号内/引号外,并且仅处理引号内的内容。但是,如果存在奇数个引号(不匹配的引号),则忽略最后一个引号。

关于java - 替换字符串中特定位置的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43531711/

相关文章:

java - ArrayList - 在 ArrayList 中存储对象的多个值

regex - 允许 A-Za-z0-9 的 Ruby 正则表达式

android - 从 res/drawable 中检索字符串

swift - 字符串成员 'characters' 返回什么?

python - 字符串索引超出范围错误

java - 服务运行时如何查看tomcat日志?

java - 在 Java 9 应用程序中使用 hibernate 生成 ORM

javascript - 使用 Javascript 查找给定字符串中一系列出现的多个标点符号

Java 正则表达式验证

java - JSON 数据未加载回 ArrayList