2014-10-20 109 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) 
相关问题