I am looking to remedy the following formats or invalid formats to a working phone number:
1 (639)-234-2323 => 6392342323
2 (042)-982-2234 => 0429822234
3 0974829-928 => 0974829928
4 +83246-983-34 => +832459834
5 +836(737)-898+78 => +83673789878
I am able to use this code and I can get my results right if a certain 1-4 are given, but if 5
, I am really going nuts.
row[1] = row[1].gsub('(','').gsub(')','').gsub('-','').gsub(' ','')
This sample is used in an import file. So you can't expect a prompt to a user.
I am also open to possibly importing record with invalid format, but should just be formatted into an accepted phone number (given parentheses inside anywhere or any +
signs anywhere).
EDIT I want to have a solution to my 5
given example. Since I can't remove +
signs anywhere without removing the first one.
EDIT 2 I asked again in the comment section that I need to include such phone format:
6 (+65)92349577 => +6592348577
@WiktorStribiżew suggested the following regex: s.gsub(/\\A\\(?(\\+)|\\D+/, '\\1')
from his original answer (the accepted one)
The solution is to capture the first +
and just match all other non-digit symbols:
s.gsub(/\A(\+)|\D+/, '\1')
See the regex demo
Pattern details :
\\A(\\+)
- a +
(that is captured into a capturing group #1 since it is wrapped with capturing parentheses) at the beginning of the string ( \\A
) |
- or \\D+
- one or more characters other than a digit. The \\1
in the replacement is a backreference to the contents stored in capturing group #1, it restores the initial +
in the replacement result
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.