Home > Back-end >  How to regex in a text stream
How to regex in a text stream

Time:11-12

I'm trying to do a regex in order to match the value of img1, img2... in a text stream as follows: `

{
    "img1": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEDgUAfZ",
    "img2": "/9j/4AAQSkZJRgABAQAAAQABAAD/dCIFhZWiAAAAAAAAAAAAAAAABhY",
}

`

I tried many things and work arounds, unfortunately nothing is working.

How can I do to get only the result of the img1(ex: /9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEDgUAfZ) ? .

CodePudding user response:

You could match the key-value pairs using the regular expression

/"[^"] "\s*:\s*"([^"]*)"/g

This puts the value into a group which then can be accessed while looping through the matches, e.g.

const json = '{ "img1": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEDgUAfZ", "img2": "/9j/4AAQSkZJRgABAQAAAQABAAD/dCIFhZWiAAAAAAAAAAAAAAAABhY" }';

function getImages(json) {
  const result = [];
  const regex = /"[^"] "\s*:\s*"([^"]*)"/g;

  let match;
  while ((match = regex.exec(json)) !== null) {
    result.push(match[1]);
  }

  return result;
}

console.log(getImages(json));

CodePudding user response:

You can loop through the key value pairs, and compare the value to the previous one:

const input = [
  `{
  "img1": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEDgUAfZ",
  "img2": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEDgUAfZ"
"
}`,
  `{
  "img1": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEDgUAfZ",
  "img2": "/9j/4AAQSkZJRgABAQAAAQABAAD/dCIFhZWiAAAAAAAAAAAAAAAABhY"
}`,
  ];
const regex = /"(img[0-9])": *"([^"] )/g;

input.forEach(json => {
  let match;
  let previousValue;
  json.replace(regex, function(m, key, value) {
    if(previousValue) {
      match = (value === previousValue);
    }
    previousValue = value;
  });
  console.log(json   ' => '   match);
});

Output:

{
  "img1": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEDgUAfZ",
  "img2": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEDgUAfZ"
} => true
{
  "img1": "/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEDgUAfZ",
  "img2": "/9j/4AAQSkZJRgABAQAAAQABAAD/dCIFhZWiAAAAAAAAAAAAAAAABhY"
} => false
  • Related