Javascript正则表达式:测试字符串以进行智能查询
我有一个保存用户输入的字符串。该字符串可以包含各种类型的数据,例如:
- 六位数字的 ID
- 包含 4 位数字和两个字母数字字符的邮政编码
- 名称(仅限字符)
当我使用此字符串搜索数据库时,将确定查询类型关于搜索类型,我想使用 JavaScript 处理服务器端(是的,我正在使用 JavaScript 服务器端)。在 StackOverflow 上搜索,给我带来了一些有趣的信息,比如 .test-method,它似乎非常适合我的需求。测试方法根据使用正则表达式对象对字符串的评估返回 true 或 false。
我使用此页面作为参考: http://www.javascriptkit.com/jsref/regexp.shtml
所以我正在尝试通过使用以下非常菜鸟的正则表达式来确定邮政编码。
var r = /[A-Za-z]{2,2}/
据我所知,这应该将字母数字字符的出现次数限制为最多两个。请参阅我的 JavaScript 控制台的输出下方。
> var r = /[A-Za-z]{2,2}/
> var x = "2233AL"
> r.test(x)
true
> var x = "2233A"
> r.test(x)
false
> var x = "2233ALL"
> r.test(x)
true /* i want this to be false */
>
如果有一点帮助,我们将不胜感激!
I have a string that holds user input. This string can contain various types of data, like:
- a six digit id
- a zipcode that contains out of 4 digits and two alphanumeric characters
- a name (characters only)
As I am using this string to search through a database, the query type is determined on the type of search, which i want to handle serverside using JavaScript (yes, I am using JavaScript serverside). Searching on StackOverflow, brought me some interesting information, like the .test-method, which seems perfect for my needs. The test-method returns either true or false based on the evaluation on the string using a regex object.
I am using this page as a reference:
http://www.javascriptkit.com/jsref/regexp.shtml
So I am trying to determine the zipcode, by using the following very noobish regex.
var r = /[A-Za-z]{2,2}/
As far I can understand, this should limit the amount of occurrences of alphanumeric characters to a maximum of two. See beneath the output of my JavaScript console.
> var r = /[A-Za-z]{2,2}/
> var x = "2233AL"
> r.test(x)
true
> var x = "2233A"
> r.test(x)
false
> var x = "2233ALL"
> r.test(x)
true /* i want this to be false */
>
A little help would be really appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第 1 部分:([^az]|^) ... 没有字母或字符串开头
第 2 部分:[az]{2} ... 两个字母
第 3 部分:([^az]|$) ... 没有字母或字符串结尾
/i ... 不区分大小写
part 1: ([^a-z]|^) ... no letter or start of the string
part 2: [a-z]{2} ... two letters
part 3: ([^a-z]|$) ... no letter or end of the string
/i ... case insensitive
不,这表示 AZ 或 az 中应该至少有两个字母,并且它们必须是连续的。比赛之前或之后也可能有更多字母。语法
{2,2}
也是多余的 - 您可以简单地使用{2}
,这意味着同样的事情。此正则表达式确保 AZ 或 az 中最多有两个字母:
这表示一个或多个数字后跟两个字母:
请注意在这两种情况下使用锚点以确保匹配之前或之后没有任何其他字符。
No, that says there should be at least two letters in A-Z or a-z and that they must be consecutive. There may also be more letters before or after the match. The syntax
{2,2}
is also redundant - you can use simply{2}
which means the same thing.This regular expression ensures a maximum of two letters in A-Z or a-z:
This one says one or more digits followed by exactly two letters:
Notice the use of anchors in both cases to ensure that there aren't any other characters before or after the match.