How can I replace specifc characters only within a substring in powershell

I am trying to process a file that is comma-delimited. Within that file, one of the fields contains commas. I have no control over the output of the file, but the field containing the commas is conveniently surrounded by curly brackets. I need to find a way in Powershell (v3) to replace the commas that exist ONLY between the curly brackets. I have tried to do a split/replace and RegEx to no avail.

Here is an example of the data:

"email@emailaddress.com","Text-exists-here()","","123456789","11/01/2015","{"ProblemSpot":"","SubstringField1":"Related Text","SubstringField2":"","SubstringFieldn":"MoreRelatedText"}","MoreData","LastField",

What I would like is an output like this:

"email@emailaddress.com","Text-exists-here()","","123456789","11/01/2015","{"ProblemSpot":""~"SubstringField1":"Related Text"~"SubstringField2":""~"SubstringFieldn":"MoreRelatedText"}","MoreData","LastField",

I've tried RegEx:

(gc $file) | -replace "{.+?(,+?).+}", "|" | set-content $file

And I've tried a rather long, ugly, hacked split/replace/join solution that works in Powershell v4, but not v3. If possible, I'd love a simple/clean solution to do a replace within the substring.


In a .NET regex, you can make use of a variable-width look-behind and a lookahead:

(?<="{[^{}]*),(?=[^{}]*}")

See regex demo (replace with ~ or any other characters of your choice)

The regex matches any , that is preceded with "{ and then any number of characters other than { and } , and that is followed with any number of characters other than { and } up to }" .

Another regex you can use:

,(?=[^{}]*})

This will match any comma that is followed by any number of characters other than { or } up to } .


One option:

$text = 
'"email@emailaddress.com","Text-exists-here()","","123456789","11/01/2015","{"ProblemSpot":"","SubstringField1":"Related Text","SubstringField2":"","SubstringFieldn":"MoreRelatedText"}","MoreData","LastField",'

$parts = $text.split('{}')

"$($parts[0]){$($parts[1].replace(',','~'))}$($parts[2])"

"email@emailaddress.com","Text-exists-here()","","123456789","11/01/2015","{"ProblemSpot":""~"SubstringField1":"Related Text"~"Substri
ngField2":""~"SubstringFieldn":"MoreRelatedText"}","MoreData","LastField",

That will split the line at the curly braces so you can isolate the section you need to do the replace on, do the replace, then re-assemble it restoring the curly braces. No regex, just simple literal text manipulations.

链接地址: http://www.djcxy.com/p/59516.html

上一篇: 用特定内容替换自定义括号

下一篇: 我如何才能在powershell中的子字符串中替换特定字符