我正在尝试处理以逗号分隔的文件。在该文件中,其中一个字段包含逗号。我无法控制文件的输出,但包含逗号的字段方便地用大括号括起来。我需要在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。如果可能的话,我会喜欢一个简单/干净的解决方案来在子串中进行替换。
答案 0 :(得分:1)
一个选项:
$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",
这会将花括号分开,这样你就可以隔离你需要进行替换的部分,进行替换,然后重新组装它来恢复花括号。没有正则表达式,只是简单的文字文本操作。
答案 1 :(得分:1)
在.NET正则表达式中,您可以使用可变宽度的后视和前瞻:
(?<="{[^{}]*),(?=[^{}]*}")
请参阅regex demo(替换为~
或您选择的任何其他字符)
正则表达式匹配前面有,
的任何"{
,然后匹配{
和}
以外的任意数量的字符,后跟任意数量的字符除了{
和}
,最高为}"
。
您可以使用的另一个正则表达式:
,(?=[^{}]*})
这将匹配除{
或}
以外}
以外的任意数量的字符后跟随的任何逗号。