我正在尝试解析一个字符串,以删除数字之间的逗号。请求您阅读完整的问题,然后请回答。
让我们考虑以下字符串。原样:))
John喜欢蛋糕,他总是通过拨打#9; 989,444 1234"来命令他们。约翰的证书如下" "姓名":" John"," Jr"," Mobile":" 945,234,1110"
假设我在java字符串中有上述文本行,现在,我想删除数字之间的所有逗号。我想在同一个字符串中替换以下内容: " 945,234,1110"与" 9452341110" " 945,234,1110"与" 9452341110" 不对字符串进行任何其他更改。
我可以遍历循环,当找到逗号时,我可以检查前一个索引和下一个索引的数字,然后可以删除所需的逗号。但它看起来很难看。不是吗?
如果我使用Regex" [0-9],[0-9]"然后我会在逗号之前和之后松开两个字符。
我正在寻求一种有效的解决方案而不是蛮力的搜索和替换"完整的字符串。实时字符串长度为~80K char。谢谢。
答案 0 :(得分: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"
答案 1 :(得分:1)
此正则表达式使用正向后看和正向前瞻仅匹配前面数字和后续数字的逗号,而不包括匹配中的这些数字:< / p>
(?<=\d),(?=\d)
答案 2 :(得分:0)
你可以像这样编写正则表达式:
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