国家代码的正则表达式 [英] Regex for country code

查看:173
本文介绍了国家代码的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为国家/地区代码编写一个正则表达式,该代码最多应限制为四个字符,只允许符号为+符号。当使用+时,+必须在开头,并且它应该至少有一个数字。

I'm trying to write a regex for country code, which should limit to four characters maximum, only symbol allowed is a + sign. When the + is used, the + has to be in the beginning, and it should have at least one number.

有效案例

+1
1
+12
12
+123
1234

无效案件

+
+1234
12345
1+
12+
<empty>
etc.

我现在的表达。

/(\+\d{1,3})/

它可以更优雅吗?

- 提前谢谢!!

-Thank you in advance!!

推荐答案

这应该有效。我用了

/^(\+?\d{1,3}|\d{1,4})$/

查看结果

编辑:

// gm标志分别是全局多行。如果您的字符串可以有多个地方匹配国家/地区代码,或者您的字符串中有多行,则需要这些字符串。如果你的字符串不仅仅是一个可能的国家代码,你需要摆脱 ^ $ 在正则表达式的开头和结尾。要使用正则表达式,你需要这样的东西:

The //gm flags are global and multiline, respectively. You need those if you have a string that can have multiple places to match a country code, or there are multiple lines in your string. If your string is going to be more than just a possible country code, you'd need to get rid of the ^ and $ at the beginning and end of the regex. To use the regex, you'd want something like this:

var regex = /^(\+?\d{1,3}|\d{1,4})$/gm
var str = "+123"
var match = str.match(regex);
//match is an array, with one result in this case. So match[0] == "+123"

这篇关于国家代码的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆