I have phone numbers like 41 000 0000 000
and currently I only can keep
sign with my code but I also need to remove spaces from this numbers.
Here is my current function
String flattenPhoneNumber(String phoneStr) {
return phoneStr.replaceAllMapped(RegExp(r'^(\ )|D'), (Match m) {
return m[0] == " " ? " " : "";
});
}
How can I remove spaces as well as keeping my
signs?
CodePudding user response:
You don't need regex for this, you can use replaceAll
method and replace all spaces with '':
String phoneStr = " 41 000 0000 000";
phoneStr = phoneStr.replaceAll(' ', '');
print(phoneStr); // 410000000000
CodePudding user response:
You can use
String flattenPhoneNumber(String phoneStr) {
return phoneStr.replaceAll(RegExp(r'(?!^\ )\D'), '');
}
The following
print(flattenPhoneNumber(" 41 000 0000 000"));
prints 410000000000
.
See the regex demo. The (?!^\ )\D
pattern matches any non-digit char (\D
) that is not equal to
at the start of the string.
CodePudding user response:
Solved
I've changed my code to following and its working as it supposed to:
String flattenPhoneNumber(String phoneStr) {
return phoneStr.replaceAll(' ', '').replaceAllMapped(RegExp(r'^(\ )|D'), (Match m) {
return m[0] == " " ? " " : "";
});
}