mystack
mystack

Reputation: 5542

Regular expression to convert string to dictionary format using powershell

i have a string as given below

$mystring="t={p:391C4D8E-9A45-42BF-9EF2-22CC5AFD941F,q:a&b,r:rut_ggrpg-1x,a:123.c.in/dev1}"

i want to convert it using the reular expression to the below format

t={'p':'391C4D8E-9A45-42BF-9EF2-22CC5AFD941F','q':'a&b','r':'rut_ggrpg-1x','a':'123.c.in/dev1'}"

I tried it using the following code but it didn't worked

$mystring -replace '([^{,]+):([^,}])+',"'`$1':'`$2'"

Upvotes: 0

Views: 219

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200503

Something like this should work:

$mystring -replace '\{',"{'" -replace '\}',"'}" -replace '([:,])',"'`$1'"

The first replacement ('\{',"{'", i.e. \{{') replaces an opening curly bracket with an opening curly bracket followed by a single quote. The second replacement ('\}',"'}", i.e. \}'}) replaces a closing curly bracket with a closing curly bracket preceeded by a single quote. The last replacement ('([:,])',"'`$1'", i.e. ([:,])'$1') replaces all colons and commas with a colon/comma between single quotes.

PS C:\> $s = "t={p:391C4D8E-9A45-42BF-9EF2-22CC5AFD941F,q:a&b,r:rut_ggrpg-1x,a:123.c.in/dev1}"
PS C:\> $s -replace '\{',"{'" -replace '\}',"'}" -replace '([:,])',"'`$1'"
t={'p':'391C4D8E-9A45-42BF-9EF2-22CC5AFD941F','q':'a&b','r':'rut_ggrpg-1x','a':'123.c.in/dev1'}

Upvotes: 1

Kamehameha
Kamehameha

Reputation: 5488

Try this -

Regex   -  ([^{,:]+)\:([^,}]+)
Replace -  '$1':'$2'

Demo here

Upvotes: 1

Related Questions