2014-10-20 115 views
0

我想解析一個字符串,以刪除數字之間的逗號。請求您閱讀完整的問題,然後請回答。Java正則表達式從字符串中刪除數字之間的逗號

讓我們考慮下面的字符串。按原樣:)

約翰喜歡蛋糕,他總是通過撥打「9894444 1234」來訂購。約翰憑據如下」 ‘名稱’:‘約翰’,‘JR’,‘手機’:‘945,234,1110’

假設我有文字的一個java字符串上線,現在,我想我想用相同的字符串替換下列內容: 「945,234,1110」與「9452341110」 「945,234,1110」與「9452341110」 而不對字符串進行任何其他更改。

我可以遍歷循環,當找到逗號時,我可以檢查前一個索引和下一個索引的數字,然後可以刪除所需的逗號,但它看起來很難看,是不是?

如果我使用正則表達式「[0-9],[0-9]」,那麼我會鬆開兩個字符,逗號前後。

我正在尋求一種有效的解決方案,而不是在整個字符串上進行強力「搜索和替換」。實時字符串長度約爲80K字符。謝謝。

回答

5
public static void main(String args[]) throws IOException 

    { 

     String regex = "(?<=[\\d])(,)(?=[\\d])"; 
     Pattern p = Pattern.compile(regex); 
     String str = "John loves cakes and he always orders them by dialing \"989,444 1234\". Johns credentials are as follows\" \"Name\":\"John\", \"Jr\", \"Mobile\":\"945,234,1110\""; 
     Matcher m = p.matcher(str); 
     str = m.replaceAll(""); 
     System.out.println(str); 
    } 

輸出

John loves cakes and he always orders them by dialing "989444 1234". Johns credentials are as follows" "Name":"John", "Jr", "Mobile":"9452341110" 
+0

另一個正確的解決方案。謝謝安庫爾 – kris123456 2014-10-20 05:40:47

+0

+1。你不需要一個字符集('[]')。 (?<= \\ d)會工作得很好:) – TheLostMind 2014-10-20 05:49:57

0

你couldtry正則表達式是這樣的:

public static void main(String[] args) { 
     String s = "asd,asdafs,123,456,789,asda,dsfds"; 
     System.out.println(s.replaceAll("(?<=\\d),(?=\\d)", "")); //positive look-behind for a digit and positive look-ahead for a digit. 
// i.e, only (select and) remove the comma preceeded by a digit and followed by another digit. 
    } 

O/P:

asd,asdafs,123456789,asda,dsfds 
+0

這是正確的解決方案。簡單而優雅。謝謝。 – kris123456 2014-10-20 05:39:48

+1

小心...... letter_的_negative lookahead與digit_的_positive lookahead不同。根據您的輸入字符串,此解決方案可能無法正常工作... – 2014-10-20 05:42:38

+0

@TroyGizzi - 你說得對。改變了它。謝謝:) – TheLostMind 2014-10-20 05:44:56

1

此正則表達式使用POSI略去回顧後正先行到只匹配與前面的位和一個位數以下逗號,而不包括在比賽本身這些數字:

(?<=\d),(?=\d) 
相關問題