[英]Regex: Replace first comma of every line with tab
I am trying to Replace first comma of every line with a tab so that the values will align.我正在尝试用制表符替换每一行的第一个逗号,以便值对齐。 I have been trying but below regex I have been testing is not leading me to the correct way.我一直在尝试,但是在我一直在测试的正则表达式之下并没有引导我找到正确的方法。
$data -replace "^[^,]*\,{1}","`t`t`t"
$data -replace ",(.*){1}","`t`t"
Raw:
First Name Then Last,Exported,Exported,Exported,Exported,Exported,Exported,Exported
Another Long Name,Exported,Exported,Exported,Exported,[______],[______],[______]
Short Name,Exported,Exported,Exported,Exported,Exported,[______],[______],[______]
Name Another Name Last,Exported,Porgress,[______],[______],[______],[______],[______]
Needed Output:
First Name Then Last, Exported,Exported,Exported,Exported,Exported,Exported,Exported
Another Long Name, Exported,Exported,Exported,Exported,[______],[______],[______]
Short Name,Exported, Exported,Exported,Exported,Exported,[______],[______],[______]
Name Another Name Last, Exported,Porgress,[______],[______],[______],[______],[______]
You can replace the first comma with a tab using您可以使用制表符替换第一个逗号
$data -replace '^([^,]*),', "`$1`t"
Here, ^([^,]*),
matches start of string, then captures into Group 1 any zero or more chars other than ,
and then a comma, and replaced with Group 1 backreference ( $1
) and the tab char.在这里, ^([^,]*),
匹配字符串的开头,然后将除 之外的任何零个或多个字符捕获到第 1 组,
然后是逗号,并替换为第 1 组反向引用 ( $1
) 和制表符。
Alternatively, use a lookbehind:或者,使用lookbehind:
$data -replace "(?<=^[^,]*),", "`t"
Here, (?<=^[^,]*),
matches a ,
that is immediately preceded with any 0+ non-comma chars from the start of string.在这里, (?<=^[^,]*),
匹配 a ,
它紧跟在字符串开头的任何 0+ 个非逗号字符之前。
If you want to insert a tab char after the comma that has six more commas after it, you can use如果你想在逗号后面插入一个制表符,后面还有六个逗号,你可以使用
$data = 'First Name Then Last, Exported,Exported,Exported,Exported,Exported,Exported,Exported'
$data -replace ',\s*(?=(?:[^,]*,){6}[^,]*$)', "`$&`t"
# => First Name Then Last, Exported,Exported,Exported,Exported,Exported,Exported,Exported
Here, ,\s*(?=(?:[^,]*,){6}[^,]*$)
matches a ,
, then zero or more whitespaces that are followed with six occurrences of 0+ non-comma chars followed with a comma and then any zero or more chars other than a comma till the end of string.在这里, ,\s*(?=(?:[^,]*,){6}[^,]*$)
匹配一个,
,然后是零个或多个空格,后面跟着六次出现的 0+ 非逗号字符后跟逗号,然后是除逗号之外的任何零个或多个字符,直到字符串结尾。
If $data
is already an array of strings (lines), then I would use -split
and join
for this:如果$data
已经是一个字符串数组(行),那么我将使用-split
并join
:
$data | ForEach-Object { ($_ -split ',', 2) -join "`t" }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.