Reputation: 21
I have tried to use regex in JAVA for replacing any funny character in a string for mobile numbers, however, it doesnt seems to be able to remove the '-' between the numbers
here is my code,
// Remove all (,),-,.,[,],<,>,{,} from string
myMobileNumber.replaceAll("[^\\d]", "");
example 65-12345678
it will still allows the - to go through without deleting it away. =(
Upvotes: 2
Views: 447
Reputation: 523584
You should reassign the result. A String is an immutable object, and all methods including .replaceAll
won't modify it.
myMobileNumber = myMobileNumber.replaceAll("[^\\d]", "");
(BTW, the pattern "\\D"
is equivalent to "[^\\d]"
.)
Upvotes: 5