Click here to Skip to main content
14,775,008 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Guys, i have a concern related to regex parsing.

here is requirement, match string data through regex and convert matching data into JSON format

i have data in below string format and i need to parse matching data into json

PC : 10%  Mat PC : 10%  DN : 20%
PC : 10%  Mat PC : 10%  OP Mat : 10%
PC : 10%  Mat PC : 10%  PH : 10%
PC : 10%  Mat PC : 10%  PH : 20%
PC : 10%  Mat PC : 10%  PH : 20% DN : 20%
PC : 10%  Mat PC : 10%  PH : 30%
PC : 10%  Mat PC : 10%  PH : 30%  DN : 20%
PC : 10%  Mat PC : 10%  PH : 30%  OP Mat : 10%

expected output in below format
[
{
"PC":"10%",
"Mat PC":"10%",
"DN":"20%"
},
{
"PC":"10%",
"Mat":"10%",
"OP Mat":"10%"
},
{
"PC":"10%",
"Mat PC":"10%",
"PH":"20%"
},
{
"PC":"10%",
"Mat PC":"10%",
"PH":"20%"
}]


What I have tried:

i wrote below pattern to match string data

(([a-zA-Z \+\.\&\/]+)(?=:)|((?<=:)[0-9 ]+(?=%))|(?<=[0-9])%)

this pattern is working perfectly on the data matching (any optimized regex pattern will be appreciated), first part i have completed to match data through regex pattern but i don't know how to parse the same in json format through regex.
Posted
Updated 28-Jul-20 3:15am
v3
Comments
OriginalGriff 28-Jul-20 4:24am
   
And what is your question?
If it's "working perfectly", then what help do you need?
Shambhoo kumar 28-Jul-20 4:37am
   
Hi Griff, Thanks for your comment.

Question is "convert matching data into json format through regex".
Dave Kreskowiak 28-Jul-20 10:17am
   
That's not a question. What part of this are you having a problem with?

Is it parsing the existing data? Is it representing the data in your code? Is it serializing the data into json? What?
F-ES Sitecore 28-Jul-20 6:57am
   
Use the RegEx class' "Matches" method to return a collection of matching hits then process them one by one building your json string. If the format of the data is always the same (same properties) then it might be easier to build a collection of objects with those properties and serialise that collection into JSON.


https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=netframework-4.8
Shambhoo kumar 28-Jul-20 8:01am
   
Hi F-ES, Thanks for your reply, that's the solution i was looking for, it's working perfectly.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900