Reputation: 501
I am trying to parse a string, to remove commas between numbers. Request you to read the complete question and then please answer.
Let us consider the following string. AS IS :)
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"
Assuming i have the above line of text in a java string, now, i would like to remove all comma's between numbers. I would like to replace the following in the same string: "945,234,1110" with "9452341110" "945,234,1110" with "9452341110" without making any other changes to the string.
I could iterate through the loop, when ever a comma is found, i could check the previous index and next index for numbers and then could delete the required comma. But it looks ugly. Doesn't it?
If i use Regex "[0-9],[0-9]" then i would loose two char, before and after comma.
I am seeking for an efficient solution rather than doing a brute force "search and replace" over the complete string. The real time string length is ~80K char. Thanks.
Upvotes: 0
Views: 5664
Reputation: 36304
You couldtry regex like this :
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
Upvotes: 0
Reputation: 2520
This regex uses a positive lookbehind and a positive lookahead to only match commas with a preceding digit and a following digit, without including those digits in the match itself:
(?<=\d),(?=\d)
Upvotes: 3
Reputation: 26067
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);
}
Output
John loves cakes and he always orders them by dialing "989444 1234". Johns credentials are as follows" "Name":"John", "Jr", "Mobile":"9452341110"
Upvotes: 5