0

I have a string as given below

$mystring="t={p:1,q:2,r:3}"

i want to convert this string to a following string

"t={'p':'1','q':'2','r':'3'}"

How can i do this in powershell

Code i tried is given below

$list=[System.Text.RegularExpressions.Regex]::Matches($mystring,"[{:,]").Value
foreach($dicitem in $diclist)
{
$dic=$dic.Replace("$dicitem","$dicitem'")
}
$list=[System.Text.RegularExpressions.Regex]::Matches($dic,"[}:,]").Value
foreach($dicitem in $diclist)
{
$dic=$dic.Replace("$dicitem","'$dicitem")
}

But iam not getting the result as expected,is there any other better way to do this

4 Answers 4

2

The -replace operator is much easier. This solution uses backreferences instead of the -f format operator.

Edit: misread the question originally (missed that the letters needed to be quoted, too. Update solution:

$mystring="t={p:1,q:2,r:3}"
$mystring -replace '([^{,]+):([^,}])+',"'`$1':'`$2'"

t={'p':'1','q':'2','r':'3'}
Sign up to request clarification or add additional context in comments.

Comments

2
$mystring -replace '(?<={.*)([a-z])|\d',("'{0}'" -f '$0')

Comments

1

try this way:

$mystring -replace '(?<={.*)([^:,}])', ("'{0}'" -f '$1')

Comments

0

Do a regex replace. Search for Regex:

(?<!\})(?!.*\{)

And replace with single quote '

Explanation of the regex:

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  (?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
    \}                       '}'
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    \{                       '{'
--------------------------------------------------------------------------------
  )                        end of look-ahead

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.