javascript - Making Regex more safe -


i'm trying turn bunch of regex more safe, mean more safe, want more accuracy.

so, i'm new regexp, , want know if i'm doing right (not regex, turn more safety).

so, i'm starting now, , first regexp want change, want push 01/2011.

past regexp:

var text    = 'inscriÇÃo: 60.537.263/0001-66 comp: 01/2011 cod rec: 150'; var reg     = /comp.*?(\d\s*)/; var match   = reg.exec(text); console.log(match[1]); 

new regexp:

var text    = 'inscriÇÃo: 60.537.263/0001-66 comp: 01/2011 cod rec: 150'; var reg     = /comp:\s([0-9]{0,2}\/[0-9]{0,4})/; var match   = reg.exec(text); console.log(match[1]); 

why this? text part of huge text, need accuraci.

other question turn regex optional, if doesn't match anything, return undefined.

thanks.

according feedback:

i want push value 2 numbers, 1 / , 4 numbers

you can use

/\bcomp:\s*(\d{2}\/\d{4})(?!\d)/g 

the \b word boundary, 5comp won't matched.

the \s* match 0 or more whitespace (if there must whitespace, use + quantifier instead).

the \d{2} match 2 digits.

the \d{4} match 4 digits , no more because of look-ahead (?!\d). look-ahead makes sure there no digit after 4 previous digits. may use \b here ensure matching word boundary.

arr = [];  var re = /\bcomp:\s*(\d{2}\/\d{4})(?!\d)/g;   var str = 'comp:10/9995, comp: 21/1234, comp: 21/123434, regcomp: 21/1234';  var m;     while ((m = re.exec(str)) !== null) {      arr.push(m[1]);  }  console.log(arr);


Comments