lua:模式匹配和提取电话号码 [英] lua: pattern matching and extracting a phone number
问题描述
在制作Lua中具有以下要求的功能时遇到麻烦:
I am having trouble crafting a function that has the following requirements in Lua:
- 以字符串
phone_number
和2位数字country_code
作为输入. -
phone_number
的格式为{1 || "} {country_code
} {10或11位手机号码}
- Takes a string
phone_number
and 2-digitcountry_code
as input. phone_number
has the form {1 || ""}{country_code
}{10 or 11-digit mobile number}
我需要10或11位手机号码作为输出.
I need as output the 10 or 11-digit mobile number.
示例I/O:
phone_number
="552234332344",country_code
="55" =>"2234332344"
phone_number
= "552234332344", country_code
= "55" => "2234332344"
phone_number
="15522343323443",country_code
="55" =>"22343323443"
phone_number
= "15522343323443", country_code
= "55" => "22343323443"
谢谢!
推荐答案
尝试"(1?)(%d%d)(%d+)"
.在您的示例中使用它:
Try "(1?)(%d%d)(%d+)"
. Using this with your examples:
print(("15522343323443"):match("(1?)(%d%d)(%d+)"))
print(("5522343323443"):match("(1?)(%d%d)(%d+)"))
将打印:
1 55 22343323443
55 22343323443
如果电话号码中恰好需要10或11位数字,则指定%d
10次,然后添加%d?
. %d
是与任何数字匹配的字符类,问号修饰符与前一个字符或字符类0或1次匹配.
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.
这篇关于lua:模式匹配和提取电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!