lua:模式匹配和提取电话号码



我在Lua中创建一个具有以下要求的函数时遇到了问题:

  • 以字符串phone_number和2位country_code作为输入
  • phone_number的形式为{1||"}{country_code}{10或11位数字的手机号码}

我需要10或11位的手机号码作为输出。

示例I/O:

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

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

谢谢!

尝试"(1?)(%d%d)(%d+)"。使用这个例子:

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

将打印:

1   55  22343323443
55  22343323443

如果您的电话号码中正好需要10或11位数字,请指定%d 10 10次,然后添加%d?%d是匹配任何数字的字符类,问号修饰符匹配前一个字符或字符类0或1次。

试试这个

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

这个表达式适用于像1 || 9945397865这样的模式,我想你问过。

编辑:我想这适用于

  • 使用string.len('552234332344')获取字符串长度=>输出:12
  • 使用string.match ('552234332344', ^%d)匹配字符串=>输出:552234332344如果匹配
  • 使用string.sub ('552234332344', 1, 2)获取国家代码=>输出:55
  • 使用string.sub('552234332344', 3)获取电话号码=>输出:2234332344

最新更新