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

209
Views
Cómo aplicar expresiones regulares para Javascript

Estoy tratando de obtener un registro de mensajes de la aplicación Azure Insight como este

 az monitor app-insights --app [app id] --analystics-query [condition like specific message id]

Entonces recibí un mensaje como este

"mensaje": [ "Recibiendo mensaje: {"type":"CTL","traceId":"f0d11b3dbf27b8fc57ac0e40c4ed9e48","spanId":"a5508acb0926fb1a","id":{"global":"GLkELDUjcRpP4srUt9yngY","caller" :null,"local":"GLkELDUisjnGrSK5wKybht"},"eventVersion":"versión de formato","timeStamp":"2021-10-01T14:55:59.8168722+07:00","eventMetadata":{"deleteTimeStamp": null,"ttlSeconds":null,"isFcra":null,"isDppa":true,"isCCPA":true,"globalProductId":null,"globalSubProductId":null,"mbsiProductId":null},"eventBody":{ "sys":"otel","msg":"Prueba del editor de eventos centralizado con la aplicación 1 (usando el inicio de sesión)","app":{"name":"otel","service":"postHouse","status": "nombre de estado","método":"POST","protocolo":"HTTP","resp_time_ms":"250","status_code":"4"},}}"

] }

Entonces, me gustaría aplicar la expresión regular para este mensaje para obtener solo el mensaje de {"type..... to "status_code":"4"},}} y también convertirlo a formato JSON

Tengo un código como este en mi archivo .js

 Then('extract json from {string}', function(message){ message = getVal(message, this); const getmess = message.match(/{(.*)}/g); const messJson = JSON.parse(getmess); console.log(messJson); })

pero no me funciona

SyntaxError: Token \ inesperado en JSON en la posición 1

¿Cómo puedo aplicar esto en mi código en Javascript? Muchas gracias por tu ayuda

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Prueba esto. Pero tenga en cuenta que la expresión regular actual está vinculada con la sintaxis de salida del programa proporcionada. Si la salida será diferente en la estructura del contenedor, es posible que esta expresión regular ya no funcione.

 // Text from app const STDOUT = ` "message": [ "Receiving message: {"type":"CTL","traceId":"f0d11b3dbf27b8fc57ac0e40c4ed9e48","spanId":"a5508acb0926fb1a","id":{"global":"GLkELDUjcRpP4srUt9yngY","caller":null,"local":"GLkELDUisjnGrSK5wKybht"},"eventVersion":"format version","timeStamp":"2021-10-01T14:55:59.8168722+07:00","eventMetadata":{"deleteTimeStamp":null,"ttlSeconds":null,"isFcra":null,"isDppa":true,"isCCPA":true,"globalProductId":null,"globalSubProductId":null,"mbsiProductId":null},"eventBody":{"sys":"otel","msg":"Testing Centralized Event Publisher with App1 (using logback)","app":{"name":"otel","service":"postHouse","status":"status name","method":"POST","protocol":"HTTP","resp_time_ms":"250","status_code":"4"},}}" ] } `; // Match JSON part string let JSONstr = /.*\[\s*\"Receiving message:\s*(.*?)\s*\"\s*]\s*}\s*$/.exec(STDOUT)[1]; // Remove trailing comma(s) JSONstr = JSONstr.replace(/^(.*\")([^\"]+)$/, (s, m1, m2) => `${m1}${m2.replace(/\,/, "")}`); // Convert to object const JSONobj = JSON.parse(JSONstr); // Result console.log(JSONobj);

about 4 years ago · Juan Pablo Isaza Report

0

Prueba este:

 /.*?({"type":.*?,"status_code":"\d+"\})/

Cuando se usa en Javascript, la parte cubierta por paréntesis cuenta como Grupo 1, es decir:

 const messJson = JSON.parse(message.match(/.*?({"type":.*?,"status_code":"\d+"\})/)[1]);

Referencia aquí: https://regexr.com/66mf2

about 4 years ago · Juan Pablo Isaza 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!