2017-04-20 107 views
0

我有以下字符串;替换字符串中的字符,在特定位置

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

我想更换,但只有一个是里面的引号\“有一天,在哪里呀?\”。

是否有可能与正则表达式?

+0

假设这[post](http://stackoverflow.com/questions/1473155/how-to-get-data-between-quotes-in-java)是关于让单词内引号。 –

+0

你想用什么来取代它? –

+0

任何事情,例如* –

回答

1

如果您确信这始终是最后的“”你能做到这一点

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); 

希望它能帮助。

+0

哎呀,我不知道如果“,”是最后一个,感谢您的帮助。 –

+0

然后寻找“日”,而不是只有“,” – Alfakyn1

2
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());         
} 

如果有多于两个引号,则将文本拆分为quote/out引用,并且只引用引号内的进程。但是,如果有奇数的引号(不匹配的引号),则最后一个引号将被忽略。

+0

这是一个很好的答案。如果将正则表达式从'\“(。*)\”'更改为'\“([^ \”] *)\“',它也可以用于多对引号 – msandiford

+0

@msandiford我使用了'。* '(不情愿的匹配者),那是做同样的事情。 – infiniteRefactor

相关问题