I have the following string: $str = '"FirstName":"first name","LastName":"Last name","AskCatalog":false,"Nuteres":61","ZipCode":"1234"'
and I need to replace value of ,for example, FirstName:" first name
" with a variable like this
"FirstName":"$strFristname"
Can anyone show me how can I do that in PowerShell?
Thank you.
Like this:
$str -replace '("FirstName":)".*?"', "`$1`"$strFirstname`""
The pattern ("FirstName":)".*?"
matches the string "FirstName":
followed by a double quote and the shortest match of any character ( .*?
) up to the next double quote. The parentheses create a group that can be referenced by $1
in the replacement string. Due to the double quotes around the replacement string that reference must be escaped ( `$1
). The same goes for the nested double quotes ( `"
).
If you want the variable instead of its value to show up in the result, you need to escape the $
of the variable as well:
$str -replace '("FirstName":)".*?"', "`$1`"`$strFirstname`""
Demonstration:
PS C:\>
PS C:\>
PS C:\>
"FirstName":"Joe","LastName":"Last name"
PS C:\>
"FirstName":"$strFirstname","LastName":"Last name"
为什么不保持简单?
$str -replace 'First Name', $strFirstname
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.