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

我正在处理一个逗号分隔的文件。 在该文件中,其中一个字段包含逗号。 我无法控制文件的输出,但包含逗号的字段方便地被大括号括起来。 我需要在Powershell(v3)中找到一种方法来替换只存在于大括号之间的逗号。 我试图做拆分/替换和RegEx无济于事。

这是一个数据的例子:

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

我想要的是这样的输出:

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

我试过RegEx:

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

我试过了一个相当长的,丑陋的,黑客入侵的拆分/替换/加入解决方案,它可以在Powershell v4中运行,但不是v3。 如果可能的话,我会喜欢简单/干净的解决方案来在子字符串中进行替换。


在.NET正则表达式中,您可以使用可变宽度后视和前视:

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

请参阅正则表达式演示(替换为~或您选择的任何其他字符)

正则表达式匹配任何,其前面有"{然后任意数量比其它字符{} ,并且其后面是与任何数量的比其它字符{}高达}"

另一个正则表达式,你可以使用:

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

这将匹配后跟任何数量以外的任何字符的逗号{}高达}


一种选择:

$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",

这将在花括号中分割线,以便您可以将需要进行替换的部分分开,进行替换,然后重新组装它以恢复花括号。 没有正则表达式,只是简单的文字文本操作。

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

上一篇: How can I replace specifc characters only within a substring in powershell

下一篇: replace first and last occurrence of a character