2017-04-20 104 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

相關問題