我试图解析一个字符串,以删除数字之间的逗号。要求您阅读完整的问题,然后回答。

让我们考虑以下字符串。原样:)

约翰喜欢蛋糕,他总是通过拨打“ 989,444 1234”来订购蛋糕。约翰的证书如下”
“名称”:“约翰”,“小”,“移动”:“ 945,234,1110”

假设我在Java字符串中有上述文本行,现在,我想删除数字之间的所有逗号。我想在同一字符串中替换以下内容:
“ 945,234,1110”和“ 9452341110”
“ 945,234,1110”和“ 9452341110”
无需对字符串进行任何其他更改。

当找到逗号时,我可以遍历循环,可以检查上一个索引和下一个索引中的数字,然后可以删除所需的逗号。但是看起来很丑。是不是

如果我使用正则表达式“ [0-9],[0-9]”,那么我将在逗号前后释放两个字符。

我正在寻找一种有效的解决方案,而不是对整个字符串进行强力的“搜索和替换”。实时字符串长度为〜80K字符。谢谢。

最佳答案

 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"

10-04 11:45
查看更多