Search code examples
lualua-patterns

lua: pattern matching and extracting a phone number


I am having trouble crafting a function that has the following requirements in Lua:

  • Takes a string phone_number and 2-digit country_code as input.
  • phone_number has the form {1 || ""}{country_code}{10 or 11-digit mobile number}

I need as output the 10 or 11-digit mobile number.

Example I/O:

phone_number= "552234332344", country_code= "55" => "2234332344"

phone_number= "15522343323443", country_code= "55" => "22343323443"

Thanks!


Solution

  • Try "(1?)(%d%d)(%d+)". Using this with your examples:

    print(("15522343323443"):match("(1?)(%d%d)(%d+)"))
    print(("5522343323443"):match("(1?)(%d%d)(%d+)"))
    

    will print:

    1   55  22343323443
    55  22343323443
    

    If you need exactly 10 or 11 digits in the phone number, then specify %d 10 times and then add %d?. %d is a character class that matches any number and question mark modifier matches the previous character or a character class 0 or 1 time.