returns null in regular expressions

4

I build a regular expression to locate a piece of text:

var re = /Incident:(.*)\tDescriptio/gm; 
var m;

while ((m = re.exec(resultados_texto)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }

}

where resultados_texto is a variable of type string to which I have given the content of a text file.

I want to get the content of group 1, that is, everything contained in (.*)

The problem is that I think the syntax is well built, but it returns me that m is null

What is the flaw in the syntax?

    
asked by kamome 18.01.2016 в 14:37
source

2 answers

2

It works in my browser: (opens the console -F12- to see the results)

var re = /Incident:(.*)\tDescriptio/gm; 
var m;

var resultados_texto = "Incident: este es el texto a buscar\tDescription:lo_que sea 140116 Drift Start Time: 14/01/2016 6:00:00 Grid File: prueba.gd";

while ((m = re.exec(resultados_texto)) !== null) {
   console.log(m[1]);
}
    
answered by 18.01.2016 в 19:03
1

You will most likely have a line break within the text, and the point in .* matches any character except the line breaks (that's why it was convenient that you put an example in the question). In other engines of regular expressions, this is easily solved by setting the DOTALL (or single-line ) mode, however in JavaScript it is not implemented. To solve it, a "trick" is used: instead of a point, [\s\S] is used, which matches all the spaces and the characters that are not spaces (that is, with any character ) .

Regular expression

/Incident:([\s\S]*?)\tDescriptio/g

demo on regex101.com

Code

var resultados_texto = "Bla Incident: incidente\nen\nvarias\nlineas\n\tDescription";
var m;

// Prueba para el ejemplo original
var re = /Incident:(.*)\tDescriptio/g; 
console.log('Regex:', re);
var resultado = [];
while ((m = re.exec(resultados_texto)) !== null) {
  if (m.index === re.lastIndex) {
    re.lastIndex++;
  }
  
  resultado.push(m); //agregar el resultado al array
}
console.log('Resultado:', resultado);

// -----------------------------

// Expresión regular propuesta
var re = /Incident:([\s\S]*?)\tDescriptio/g; 
console.log('Regex:', re);
var resultado = [];
while ((m = re.exec(resultados_texto)) !== null) {
  if (m.index === re.lastIndex) {
    re.lastIndex++;
  }
  
  resultado.push(m); //agregar el resultado al array
}
console.log('Resultado:', resultado);
    
answered by 29.07.2016 в 03:20