Issue
How do I use the re.sub python method to append +1 to a phone number?
When I use the following function it changes this string "802-867-5309" to this string "+1+15309". I'm trying to get this string "+1-802-867-5309". The examples in the docs replace show how to replace the entire string I don't want to replace the entire string just append a +1
import re
def transform_record(record):
new_record = re.sub("[0-9]+-","+1", record)
return new_record
print(transform_record("Some sample text 802-867-5309 some more sample text here"))
Solution
If you can match your phone numbers with a pattern you may refer to the match value using \g<0>
backreference in the replacement.
So, taking the simplest pattern like \d+-\d+-\d+
that matches your phone number, you may use
new_record = re.sub(r"\d+-\d+-\d+", r"+1-\g<0>", record)
See the regex demo. See more ideas on how to match phone numbers at Find phone numbers in python script.
See the Python demo:
import re
def transform_record(record):
new_record = re.sub(r"\d+-\d+-\d+", r"+1-\g<0>", record)
return new_record
print(transform_record("Some sample text 802-867-5309 some more sample text here"))
# => Some sample text +1-802-867-5309 some more sample text here
Answered By - Wiktor Stribiżew
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.