Ant*_*ine 1 regex powershell replace
我有这个脚本,在文件上做一些正则表达式替换.我不明白为什么返回的字符串删除了所有换行符?
示例文件内容(UTF-8,每行后有CR-LF):
hello
hello
hello
Run Code Online (Sandbox Code Playgroud)
剧本:
$content = Get-Content "c:\spikes\regexnewline\regexnewline.txt"
Set-Content "c:\spikes\regexnewline\regexnewline-2.txt" $content # test
$content = [regex]::Replace($content, "ll", "yy") #basic replace
Set-Content "c:\spikes\regexnewline\regexnewline-3.txt" $content
Run Code Online (Sandbox Code Playgroud)
当然,file regexnewline-2.txt是输入文件的精确副本.但是为什么regexnewline-3.txt它的内容只在一条线上,最后只有一个CR-LF?
heyyo heyyo heyyo\CR\LF
Run Code Online (Sandbox Code Playgroud)
显然我在这里遗漏了一些东西.谁能发现它?
顺便说一下,我试过玩regex.Replace并使用带有4个参数的重载RegexOptions,如MSDN所记载的那样指定,但脚本失败说这个方法没有4个参数重载.Powershell是否使用不同版本的.Net框架?
你看到这个的原因是因为$ content是你最初从文件中读取时的一个字符串数组.您可以看到任何变量的类型,如下所示:
$content.GetType().FullName
Run Code Online (Sandbox Code Playgroud)
默认情况下,Get-Content返回一个字符串数组,其中每个元素代表一行.当您将该数组传递给.NET的正则表达式替换方法时,PowerShell不会看到一个方法重载,它接受一个字符串数组,但确实看到一个接受字符串的方法,因此它将您的字符串数组强制转换为字符串.如果您在Get-Content调用后立即执行此操作,则可以看到相同的效果:
"$content"
Run Code Online (Sandbox Code Playgroud)
您甚至可以修改PowerShell在执行此操作时如何连接各个元素:
$OFS = ", "
"$content"
Run Code Online (Sandbox Code Playgroud)
而不是使用.NET正则表达式替换,尝试使用PowerShell的-replace运算符,它也处理正则表达式:
$content = $content -replace 'll','yy'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
955 次 |
| 最近记录: |