Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
regex issue
#1
basically im making a reminder app as practice. i try to use regex to verify that the phone number the user inputs is UK based. So basically the input should only start with + and end with 12 digits. However some of the entries that i make are without the + symbol. my code follows. any help is much appreciated

def save_info():
    """Save the entered reminder information if valid."""
    try:
        df = pd.read_csv("data.csv")
    except FileNotFoundError:
        with open("data.csv", "w") as file:
            writer = csv.writer(file)
            writer.writerow(["name", "date", "description", "phone number"])
        df = pd.DataFrame(columns=["name", "date", "description", "phone number"])

    date = date_ent.get()
    if check_date(date):
        name = name_ent.get().title()
        name_parts = name.split(" ")
        if len(name_parts) < 2:
            messagebox.showerror(title="Ooooooops",
                                 message="You have not entered a first and last name!!\nPlease try again!!")
            return

        desc = description_ent.get()
        phone_number = phone_ent.get()
        reg_exp = re.compile(r'^\+\d{12}$')
        if not re.match(reg_exp, phone_number):
            messagebox.showerror(title="OOOOOOps", message="You have not entered a valid phone number!!\n"
                                                           "Please enter a phone number with a valid country code starting with the + symbol.\n"
                                                           "The phone number should be 12 digits long!!\n")
            return
        if check_alphabetical(name):

            if check_alphabetical(desc):



                if messagebox.askyesno(title="Save this information?",
                                       message=f"On the {date} {name_parts[1]}, {name_parts[0]} should be reminded to {desc}!! "
                                               f"Their phone number is {phone_number}\nIs this information correct?"):
                    saved_data=df.to_dict("records")
                    saved_data.append({"name":name,"date":date,"description":desc,"phone number":phone_number})

                df2=pd.DataFrame(saved_data)
                df2.to_csv("data.csv", index=False)

                date_ent.delete(0, END)
                name_ent.delete(0, END)
                description_ent.delete(0, END)
                phone_ent.delete(0, END)
Reply
#2
You might could use pythons startswith method

phone = '+44 20 7123 4567'
phone2 = '44 20 7123 4567'
phone3 = '+41 20 7123 4567'

test = True if phone.startswith('+44') else False
test2 = True if phone2.startswith('+44') else False
test3 = True if phone3.startswith('+44') else False

print(test)
print(test2)
print(test3)
Output:
True False False
I did a little research on uk phone numbers. They look kind of complicated.
https://www.mycountrymobile.com/blog/uk-...er-format/
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
(Jun-25-2024, 12:04 PM)menator01 Wrote: You might could use pythons startswith method

phone = '+44 20 7123 4567'
phone2 = '44 20 7123 4567'
phone3 = '+41 20 7123 4567'

test = True if phone.startswith('+44') else False
test2 = True if phone2.startswith('+44') else False
test3 = True if phone3.startswith('+44') else False

print(test)
print(test2)
print(test3)
Output:
True False False
I did a little research on uk phone numbers. They look kind of complicated.
https://www.mycountrymobile.com/blog/uk-...er-format/

thats a brilliant idea. thanks a lot. I added it into my process information function and if the phone number starts with + then the sms gets constructed and sent. if not then i concatenate a plus sign to the phone number as a backup.. Thanks A LOT
Reply
#4
Glad I could help. Wink
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#5
Can do this with re.

e will match + and or 00 followed by numbers and spaces followed by the end of the string.

You can probably build e differently and still get the same result!

import re

phone = '+44 20 7123 4567'
phone2 = '44 20 7123 4567'
phone3 = '+41 20 7123 4567'
phone4 = '0044 1268 7289890'
phone5 = 'A44 1268 75677799' # no match
phone6 = '+44 1268 756ABC77799' # no match

e = re.compile(r'(\+)?(00)?([0-9 ]+)\Z')

#match(phone) only matches from the beginning of the string (search matches anywhere in the string)
#(\+)? beginning optionally followed by + (escape + because + is significant in re)
#(00)? beginning optionally followed by 00 (instead of +)
#([0-9 ]+) any sequence of numbers and spaces. Anything else will cause failure to match.
#\Z end of string
Gives:

Output:
e = re.compile(r'(\+)?(00)?([0-9 ]+)\Z') e.match(phone) <re.Match object; span=(0, 16), match='+44 20 7123 4567'> e.match(phone2) <re.Match object; span=(0, 15), match='44 20 7123 4567'> e.match(phone3) <re.Match object; span=(0, 16), match='+41 20 7123 4567'> e.match(phone4) <re.Match object; span=(0, 17), match='0044 1268 7289890'> e.match(phone5) e.match(phone6)

To catch the result:

Output:
res = e.match(phone) res.groups() ('+', None, '44 20 7123 4567') res = e.match(phone2) res.groups() (None, None, '44 20 7123 4567')
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  issue in using regex akbarza 4 714 Nov-14-2023, 10:00 AM
Last Post: buran
  Facing issue in python regex newline match Shr 6 1,720 Oct-25-2023, 09:42 AM
Last Post: Shr
  Regex Issue from Automate the Boring Stuff book robgraves 2 2,942 Jun-16-2019, 12:41 AM
Last Post: robgraves

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020