Regex to separate a string

Asked

Viewed 897 times

1

Galley I need to separate a piece of a string to put as a result of a specific class.

I have the following return

02/10/2017 a 05/10/2017 em São Paulo - Papercut MF Técnico Presencial (28 hrs) - Vagas disponíveis

I needed some regex to separate in the text at the first occurrence of a,always at the first occurrence of a, which is between the dates.

Thanks in advance

  • You can’t just use a substring ?

  • No, the return varies in size, precise of the first occurrence of the same

  • This gives an idea of how I suggested: var textDoRetorno = "02/10/2017 a 05/10/2017 em São Paulo - Papercut MF Técnico Presencial (28 hrs) - Vagas disponível"; console.log("PRIMEIRA OCORRENCIA :"+textDoRetorno.substring(0, textDoRetorno.indexof("A"))); The return, you want some input from the letter "A" or the contents until the first occurrence ?

2 answers

1


You can use the following regular expression:

/([0-9]{2}\/[0-9]{2}\/[0-9]{4}) a ([0-9]{2}\/[0-9]{2}\/[0-9]{4})/g

This expression will look for 2 numbers, followed by a bar, followed by 2 more numbers, followed by a bar again and after that, 4 more numbers. After that he will seek String a and the same combination.

var texto = "02/10/2017 a 05/10/2017 em São Paulo - Papercut MF Técnico Presencial (28 hrs) - Vagas disponíveis";

console.log(separar(texto));

function separar(texto) {
  var regex = /([0-9]{2}\/[0-9]{2}\/[0-9]{4}) a ([0-9]{2}\/[0-9]{2}\/[0-9]{4})/g;
  var resultado = [];
  var combinacao = regex.exec(texto);
  
  resultado.push(combinacao[1]);
  resultado.push(combinacao[2]);
  
  return resultado;
}

1

I understand you want to pick up a piece of a string so...

You can transform the string into an array by separating the elements by spaces:

var teste = "02/10/2017 a 05/10/2017";
var arrayTeste = teste.split(' ');

This will return an array with 3 elements:

0- 02/10/2017

1- a

2- 05/10/2017

You can pick them up separately:

arrayTeste[0];
arrayTeste[1];
arrayTeste[2];

If you want you can still use the split('/') to separate the day, month and year

Comments: The first element has position 0, the second position 1 so on

The elements will no longer have the space character ( ) because the split deletes it to separate the elements of the array

I recommend watching the videos of the white Rodrigo - https://www.youtube.com/user/rodrigobranas he has videos about js, Angularjs and nodejs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.