Javascript Regex - Longer than 9 characters, starting with "SO-" and ending with 6 numbers

Regular expressions are just evil in my mind and no matter how many times I read any documentation, I just can not understand even the simplest expressions!

I am trying to write what should be a very simple expression for querying a variable in javascript, but I just can't get it to work correctly.

I am trying to verify the following: -

The string must contain 9 characters, starting with SO- (not case sensitive, such as So-, so-, sO- and SO-), and then 6 numbers.

So everyone should be consistent

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

but the following should fail

SO-12d456, TAK-1234567

etc.

I have only left 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/>'); } 

See http://jsfiddle.net/TzHKd/ for the above example

Test number 5 matches, although it should fail because there are 7 numbers, not 6.

Any help would be greatly appreciated.

Greetings

+4
source share
2 answers

use this regex

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

without ^ (a line starting with) or $ (a line ending), you are looking for a common subscript match (which is the reason when you have 7 digits, your regular expression returns true).

+3
source

Using the ^ and $ anchors (corresponding to the beginning of the line and the end of the line, respectively), you can make the regular expression match the entire line. Otherwise, the match with return true as soon as the characters in the regular expression match.

So you apply it as follows:

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

Source: https://habr.com/ru/post/1500128/


All Articles