A
A
Amir2017-09-18 11:16:41
JavaScript
Amir, 2017-09-18 11:16:41

How to correctly form a regular expression and pull out the desired values?

Good afternoon, dear ones.
I'm having a really hard time with regular expressions, so I'm really looking forward to your help.
I get a line with errors. It looks like this:

"Error.0.Value : This is error for item 0.\r\nError.1.Value : This is error for item 1 and this item is exist."

I need an object of the form as a result:
{
  "someinput[0]": "This is error for item 0.",
  "someinput[1]": "This is error for item 1 and this item is exist."
}

and so on. I get rid of \r\n with .split("\r\n");
But here's what to do next and how to parse the string
Error.0.Value : This is an error for item 0.
I do not understand. I understand that the question is completely newbie and the solution lies on the surface, but I can't find it.
Thanks in advance for the replies.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
gleendo, 2017-09-18
@Guedda

const str = "Error.0.Value : This is error for item 0.\r\nError.1.Value : This is error for item 1 and this item is exist.";

let result = {};

str.split("\r\n").forEach(item => Object.assign(result, { [`someinput[${item.split(" : ")[0].match(/\d+/)}]`]: item.split(" : ")[1] }));

/*
{
  "someinput[0]": "This is error for item 0.",
  "someinput[1]": "This is error for item 1 and this item is exist."
}
*/

K
keslo, 2017-09-18
@keslo

var msg = "Error.0.Value : This is error for item 0.\r\nError.254.Value : This is error for item 1 and this item is exist.";

var result = {};
msg.split("\r\n").map((item, i) => { result["someinput[" +item.split(" : ")[0].match(/\d+/)[0]+ "]"] = item.split(" : ")[1]} )

console.log(result);

/*
{
  someinput[0]:"This is error for item 0.",
  someinput[254]:"This is error for item 1 and this item is exist."
}
*/

P
Pavel Kornilov, 2017-09-18
@KorniloFF

/Error\.\d+\.Value :(.+?)(?:\\r|\\n|$)/gim
https://regex101.com/r/cpffip/1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question