Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
¿Cómo ignorar espacios solo para contenido dinámico mientras se forma una expresión regular para comparar dos oraciones?

Tengo una oración y necesito compararla con el mensaje de envío del cliente y devolver si se aprobó o falló. La oración contiene {#val#}, que se puede reemplazar por cualquier valor en los mensajes de envío del cliente. La condición aquí está en lugar de {#val#} en una oración => El mensaje del cliente puede contener cualquier cosa dentro del límite de 5. {#val#} es el contenido dinámico. Otra parte de los mensajes son contenido estático. En el contenido estático del mensaje del cliente, podemos ignorar el espacio y compararlo con la oración definida.

Pero en el contenido dinámico de los mensajes de envío del cliente, ({#val#}) se deben considerar los espacios. Por ejemplo, la oración contiene {#val#}{#val#} y en el mensaje del cliente debe reemplazarse por nehradutta no nehra space dutta ya que se colocan continuamente 2 {#val#}{#val#} en la oración definida .

 var sentence = "Hi {#val#}, Thank you {#val#} {#val#} for visting us" var customermsg = "Hi asz, Thank you shaky dutta for visting us" //Should Pass as sentence and customer msg are matching var customermsg1 = "Hiasz, Thank you shaky dutta forvisting us" //Should Pass as sentence and customer msg are matching ( Ignoring the space in static portion ) var customermsg2 = "Hi asz, Thank you nehra dutta for visting us" //Should Fail since there is lot of space between the dynamic content {#val#} => (nehra dutta) places. Should contain single space since the sentence has {#val#}space{#val#}.

Necesito formar una expresión regular, que evite espacios al comparar contenido estático e incluya espacios al comparar contenido dinámico.

Actualmente, mi código está debajo reemplazando todos los espacios y comparando.

 var separators = ['#val#','#VAL#','#vaL#','#vAl#','#Val#']; var regexStr = sentence.replace(/[\ ]/g,''); var customermsg = customermsg.replace(/[\ ]/g,''); separators.forEach(str => { regexStr = regexStr.replace(new RegExp(str, 'g'), '.{0,5}') }) var regex = new RegExp(`^${regexStr }$`,"i") if (!customermsg.match(regex)) Status = "Fail" else Status = "Pass"

Amablemente ayúdenme en esto ya que soy nuevo en la expresión regular

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

 var separators = ["#val#", "#VAL#", "#vaL#", "#vAl#", "#Val#"]; let sentence = "Hi {#VAL#}, Thank you {#val#} {#val#} for visting us"; // make all spaces optional. Except "} {". regexString = sentence.replace(/(^|.)\s($|.)/g, (x, g1, g2) => (x == "} {" ? x : g1 + "\\s?" + g2)); // turn separators into .{0,5} separators.forEach((str) => { regexString = regexString.replace(new RegExp(`{${str}}`, "g"), ".{0,5}"); }); // input var customermsg = "Hi asz, Thank you nehra dutta for visting us"; //Should Pass var customermsg1 = "Hiasz, Thank you nehra dutta forvisting us"; //Should Pass var customermsg2 = "Hi asz, Thank you nehradutta for visting us"; //Should Fail let regex = RegExp("^" + regexString + "$"); console.log("REGEX ==>", regex); console.log(regex.test(customermsg) ? "Pass" : "Fail", "==>", customermsg); console.log(regex.test(customermsg1) ? "Pass" : "Fail", "==>", customermsg1); console.log(regex.test(customermsg2) ? "Pass" : "Fail", "==>", customermsg2);

over 4 years ago · Santiago Trujillo Report

0

Tuve que usar dos expresiones regulares debido a la complejidad de las condiciones, pero aquí está mi respuesta.

Expliqué la expresión regular en los comentarios.

 const separator = '{#val#}'; // This is what is used to declare dynamic content const staticSpace = new RegExp(`(?=[^.\\s*${separator}\\s*.])(\\s|.{0})`, 'i'); // This regex called staticSpace, is for those the spacing between static content, that you said should be ignored. const dynamicSpace = new RegExp(`\\s*(${separator})\\s*`, 'gi'); // This regex called dynamicSpace, is for the possible spacing between static content and dynamic content, that you said shouldn't be too long, so I figured only one space after a dynamic word is alright. // The \s* is used to mark any amount of space // The (${seperator}) will input the seperator variable, this part is crucial cus that's how dynamic content would be marked. // Then the last \s* with the same use to the first const sentence = "Hi {#val#}, Thank you {#val#} {#val#} for visting us"; // Template for the messages let customerMessages = ["Hi asz, Thank you shaky dutta for visting us", "Hiasz, Thank you shaky dutta forvisting us", "Hi asz, Thank you nehra dutta for visting us"]; // All the customerMessages let regex = new RegExp(`^${[].concat.apply([], sentence.split(staticSpace).map(a => a.includes(separator) ? a : a.split(/.{0}|\s/))).filter(e => /\S/.test(e)).join('\\s*').replace(dynamicSpace, '\\s?$1\\s?').replace(new RegExp(separator, 'gi'), '[.\\S]{0,5}')}$`, 'i'); // Firstly, I split the template to the static content to ensure that static spacing is ignored // Then I replaced all the dynamicSpace with \s?1\s? which is just for one space before and after the seperator // Then all the extra spacing, this would be static content spacing which you said can be as long as it wants and I replaced it with \s* which matches 0 or as many as possible because of static content that may be joined together // Finally, I used the seperator to match the dynamic content placeholders. [.\\S]{0,5}, this regex matches any character except a space, with a limit of 5 characters. Because you said that the dynamic content should not be longer than 5 characters // I passed the flag i to most of the replacements because of case-insensitivity. You woulnd't have to define the same seperator in different cases now console.log(customerMessages.map(message => ({ message, state: regex.test(message) ? 'Pass' : 'Fail' }))); // logging out the result

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!