【问题标题】:Replace characters in a String, in a specific location在特定位置替换字符串中的字符
【发布时间】:2017-09-17 19:22:14
【问题描述】:

我有以下字符串;

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

我想替换,,但只替换引号内的那个\“前几天,你在哪里?\”。

正则表达式可以吗?

【问题讨论】:

  • 假设 post 是关于获取引号内的单词。
  • 你想用什么替换它?
  • 任何东西,例如 *

标签: java regex string replace


【解决方案1】:
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());                                  
}

如果有两个以上的引号,这会将文本分成引号内/引号外,并且只处理引号内的内容。但是,如果有奇数个引号(不匹配的引号),则忽略最后一个引号。

【讨论】:

  • 这是一个很好的答案。如果将正则表达式从 \"(.*)\" 更改为 \"([^\"]*)\",它也适用于多对引号。
  • @msandiford 我使用了.*?(不情愿的匹配器),它做同样的事情。
【解决方案2】:

如果您确定这始终是最后一个“,”,您可以这样做

String s = "Hellow world,how are you?\"The other day, where where you?\"";
int index = s.lastIndexOf(",");
if( index >= 0 )
    s = new StringBuilder(s).replace(index , index + 1,"X").toString();
System.out.println(s);

希望对你有帮助。

【讨论】:

  • 不,我不确定“,”是否是最后一个,谢谢您的帮助。
  • 然后查找“day”,而不是仅查找“,”
猜你喜欢
  • 1970-01-01
  • 2013-05-12
  • 2017-04-10
  • 2015-05-05
  • 2021-01-27
  • 2021-09-17
  • 2015-10-18
  • 2012-07-20
  • 2011-01-15
相关资源
最近更新 更多