2016-06-07 84 views
-2

我有一個字符串像從字符串中刪除單引號,但不是從開始和結束

String abc = "'Joe's Dinner'"; 

現在我需要從中間刪除該帖,這樣的結果可以像

abc = "'Joes Dinner'" 

編輯: 我意識到問題發生在別的地方。實際上我分裂了一個5 GB的XML文件。我正在使用StAX來做到這一點。這是我的代碼。

public String split(String fileName){ 
    XMLInputFactory xif = XMLInputFactory.newInstance(); 
    XMLEventReader xer = xif.createXMLEventReader(new FileInputStream(new File(fileName))); 

    String fileContent = ""; 

    while(xer.hasNext()) { 
    XMLEvent e = xer.nextEvent(); 
    fileContent = fileContent + e.toString(); 
    } 
    return fileContent; 
} 

現在,在我的源XML行當屬

<location state="Côte d'Azur" xsi:nil="true" city="Marseille" country="FRANCE"></location> 

但在輸出屬性值雙引號更改爲單引號在分析導致的錯誤。有沒有什麼辦法保留這個雙引號。

+3

你試過在SO上搜索嗎?你能告訴我們一些代碼嗎? – TheLostMind

+0

只是'''喬的晚餐'''或者更像'「......文本文本'喬的晚餐'文本文本...」「? – gdros

+0

我實際上正在嘗試正則表達式,而我發現的其實也是選擇起始單引號。沒有運氣。 –

回答

1

如果我明白你的問題,那麼你需要類似的東西,我提出三點olutions解決您的問題,

public class Cote { 

    public static void main(String args[]) { 
     //First Solution 
     String abc = "'Joe's Dinner'"; 

     //Second Solution 
     String abc3 = "'" + abc.replace("'", "") + "'"; 
     System.out.println(abc3); 

     String abc2 = "'"; 
     for (int i = 1; i < abc.length() - 1; i++) { 
      String c = abc.charAt(i) + ""; 
      if (!c.equals("'")) { 
       abc2 += c; 
      } 
     } 
     abc2 += "'"; 
     System.out.println(abc2); 

     //Third Solution 
     abc = "<location state='Côte d'Azur' xsi:nil='true' city='Marseille' country='FRANCE'></location>"; 
     abc2 = ""; 
     int count = abc.length() - abc.replace("'", "").length(); 

     int count2 = 0; 
     for (int i = 0; i < abc.length(); i++) { 
      String c = abc.charAt(i) + ""; 
      if (c.equals("'")) { 
       count2++; 
       if (count2 == 1 || count2 == count) { 
        abc2 += c; 
       } 
      } else { 
       abc2 += c; 
      } 

     } 
     System.out.println(abc2); 
    } 
} 

好運

+0

Offtopic,但thansk! –

+0

你是什麼意思@ΦXocę웃Петпо –

0

您可以使用一個很好的功能正則表達式稱爲積極預見/後顧,這意味着您可以匹配不被視爲實際匹配部分的東西。在這種情況下,你要忽略的起點和字符串的結束字符,所以更換是:

input.replaceAll("(?<=.)'(?=.)", ""); 

當第一個括號部分內容,第二部分「以任何字符進行」表示「,其次是任何字符」。

如果你想保持的報價,而不會破壞你的XML您可能要逃避它,而不是在這種情況下,你可以使用

input.replaceAll("(?<=.)'(?=.)", "&apos;"); 

好鎖!

+0

爲什麼不使用開始和結束行檢查'(?<!^)'(?!$)' – TEXHIK

+0

這也可以正常工作;使用_negative_前瞻/後視... –