Reputation: 57
Hello guys I'm starting to learn regex and I want to replace some characters from string.
this is my test case:
Example string:
+52 924 340 2304
Expected output:
09243402304
This is what I've tried:
String number = cursor.getString(col_number).replace("\\d{2}", "");
But I can't seem to get my expected output. Any help? I would gladly appreciate your help. Thanks.
Update:
Also, I want to remove all whitespace characters from the string and I forgot to add if the string has other characters like (,),-
Upvotes: 2
Views: 4534
Reputation: 67968
^\+\d{2}[^\d]*(\d+)[^\d]*(\d+)[^\d]*(\d+)$
You can use this and then replace with
0$1$2$3
See demo.
http://regex101.com/r/iX5xR2/12
This will work for all cases
Upvotes: 0
Reputation: 22822
String number = cursor.getString(col_number).replaceAll("^\\+\\d{2}", "0").replaceAll("[^\\d]", "")
Upvotes: 1
Reputation: 784998
Your method:
.replace("\\d{2}", "");
will fail to work because in Java String#replace
doesn't take a regex. Try String#replaceAll
OR String#replaceFirst
You can use:
String number = cursor.getString(col_number).replace(" ", "").replaceFirst("\\+\\d{2}", "0");
Upvotes: 1
Reputation: 11116
use this :
.replaceAll("^[^\\s]+|\\s", "")
demo here : http://regex101.com/r/uY9xB2/1
Upvotes: 1
Reputation: 95948
@anibhava already mentioned your problem, I want to suggest another solution, you can simply remove the white spaces and cut the string using String#substring
:
number.replaceAll("\\s+", "").substring(3); //you might want to add the 0 using + operator
Upvotes: 0
Reputation: 5233
Why do you not split the String
at the whitespaces. Then you replace the first entry with a 0
, and concatenate the array parts to one String
again. Done.
Upvotes: 0