简体   繁体   English

Javascript Regex - 9个字符长,以'SO-'开头,以6个数字结尾

[英]Javascript Regex - 9 chars long, starting with 'SO-' and ending with 6 numbers

Regular expressions are simply evil in my mind and no matter how many times I read any documentation I just cannot seem to grasp even the simplest of expressions! 正则表达式在我的脑海中简直是邪恶的,无论我多少次阅读任何文档,我似乎无法掌握甚至最简单的表达!

I am trying to write what must be a very simple expression to query a variable in javascript but I just cannot get it to work properly. 我正在尝试编写一个非常简单的表达式来查询javascript中的变量,但我无法让它正常工作。

I am trying to validate the following:- 我想验证以下内容: -

The string must be 9 characters long, starting with SO- (case insensitive eg So-, so-, sO- and SO-) followed by 6 numbers. 字符串长度必须为9个字符,以SO-开头(不区分大小写,例如So-,so-,sO-和SO-),后跟6个数字。

So the following should all match 所以以下都应该匹配

SO-123456, So-123456, sO-456789, so-789123 SO-123456,So-123456,sO-456789,so-789123

but the following should fail 但以下情况应该失败

SO-12d456, SO-1234567 SO-12d456,SO-1234567

etc etc 等等

I have only managed to get this far so far 到目前为止,我只能做到这一点

var _reg = /(SO-)\d{6}/i;

var _tests = new Array();
_tests[0] = "So-123456";
_tests[1] = "SO-123456";
_tests[2] = "sO-456789";
_tests[3] = "so-789123";
_tests[4] = "QR-123456";
_tests[5] = "SO-1234567";
_tests[6] = "SO-45k789";

for(var i = 0; i < _tests.length; i++){
  var _matches = _tests[i].match(_reg);
  if(_matches && _matches.length > 0)
     $('#matches').append(i+'. '+_matches[0] + '<br/>');
}

Please see http://jsfiddle.net/TzHKd/ for above example 有关上面的示例,请参阅http://jsfiddle.net/TzHKd/

Test number 5 is matching although it should fail as there are 7 numbers and not 6. 测试编号5是匹配的,但它应该失败,因为有7个数字而不是6。

Any assistance would be greatly appreciated. 任何帮助将不胜感激。

Cheers 干杯

use this regexp instead 请改用此正则表达式

/^(so-)\d{6}$/i;

without ^ (string starting with) or $ (string ending with) you're looking for a generic substring match (that's the reason why when you have 7 digits your regexp return true). 如果没有^ (以字母开头的字符串)或$ (以字符串结尾 ),你正在寻找一个通用的子字符串匹配(这就是为什么当你有7位数时你的regexp返回true)。

By using the anchors ^ and $ (matching beginining of line and end of line respectively), you can make the regex match the whole line. 通过使用锚点^$ (分别匹配行和行尾的开头),可以使正则表达式匹配整行。 Otherwise, the match with return true as soon as the characters in the regex are matched. 否则,只要正则表达式中的字符匹配,匹配就返回true。

So, you will apply it like this: 所以,你会像这样应用它:

var _reg = /^(so-)\d{6}$/i;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM