1

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!

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Neil
  • 7,042
  • 9
  • 43
  • 78

2 Answers2

3

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.

Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
-1

Try this

^[0-9]{1,3}\s\|{2}\s[0-9]{10,11}$

This expression is for pattern like 1 || 9945397865 like you asked i guess . .

EDITED: I guess this works

  • fetch string length using string.len('552234332344') => Output: 12
  • match string using string.match ('552234332344', ^%d) => Output: 552234332344 if matches
  • fetch country code using string.sub ('552234332344', 1, 2) => Output: 55
  • fetch phone no. using string.sub('552234332344', 3) => Output: 2234332344
kushalbhaktajoshi
  • 4,640
  • 3
  • 22
  • 37
  • What's the lua-compatible version? i.e. using patterns (http://www.lua.org/manual/5.1/manual.html#5.4.1) – Neil Sep 06 '12 at 07:31
  • That's a regular expression; not a lua pattern. – daurnimator Sep 12 '12 at 09:16
  • @daurnimator read the whole answer before you respond bro . . i guess you missed the edited answer . . :) – kushalbhaktajoshi Sep 13 '12 at 04:37
  • the edited answer is rather unclear though.... you also missed the fact you could do: `%d%d?%d?` to replicate the behaviour of {1,3}. – daurnimator Sep 14 '12 at 13:55
  • @daurnimator while coding you need to make some shortcut ways . . think about less execution time . . `{1,3}` gets rendered much faster than `%d%d%d` . . Everybody can code . . but nobody thinks about the execution time . . :) – kushalbhaktajoshi Sep 14 '12 at 14:39