在Powershell中.replace和-replace有什么区别? [英] What's the difference between .replace and -replace in powershell?

查看:158
本文介绍了在Powershell中.replace和-replace有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给我的印象是.replace和-replace是完全相同的东西,但是我发现我无法使用-replace来完成一些使用.replace的RegEx任务.有人可以指出我想念的东西吗?

Broken Regex replace:
$a=$a.Replace('.:\\LOGROOT\\', "\\$env:computername\logroot\")


Working Regex replace:
$a=$a -Replace('.:\\LOGROOT\\', "\\$env:computername\logroot\")

ps: 以下URL使我认为我不熟悉.replace选项,但是我似乎找不到有关如何使用它们或如何访问这些选项帮助的任何其他信息. http://www.computerperformance.co.uk/powershell/powershell_regex.htm Regex.Replace(String,String,String,RegexOptions)以及: Regex.Replace(String,String,MatchEvaluator,RegexOptions)方法.

谢谢

解决方案

@Keith Hill的答案解释了Replace方法和-replace运算符之间的区别,以解释为什么您可能看不到相同的结果,它是因为您使用的是String.Replace方法进行字符串替换,而-replace运算符使用正则表达式替换.为此,您可以使用 Regex.Replace 方法,您应该看到相同的效果:

[regex]::replace($a,'.:\\LOGROOT\\', "\\$env:computername\logroot\")

简而言之,-replace运算符与Regex.Replace相同(上面链接了特定的重载),但通常Replace()可以是实例或静态方法,可以执行与-replace完全不同的任何事情

I was under impression that .replace and -replace were the exact same thing, however I found that I could not accomplish some RegEx tasks with .replace that I could with -replace. Could someone please point out what I'm missing?

Broken Regex replace:
$a=$a.Replace('.:\\LOGROOT\\', "\\$env:computername\logroot\")


Working Regex replace:
$a=$a -Replace('.:\\LOGROOT\\', "\\$env:computername\logroot\")

ps: The following URL leads me to think there are .replace options I am unfamiliar with, but I cant seem to find any additional information on how to use them, or how to access the help for these options. http://www.computerperformance.co.uk/powershell/powershell_regex.htm Regex.Replace(String, String, String, RegexOptions) and also: Regex.Replace(String, String, MatchEvaluator, RegexOptions) methods.

Thank you

解决方案

While @Keith Hill's answer explains the difference between Replace method and the -replace operator, to explain why you might not see the same result, it is because you are using the String.Replace method which does string replace and -replace operator uses regex replace. You can use the Regex.Replace method for this purpose and you should see the same effect:

[regex]::replace($a,'.:\\LOGROOT\\', "\\$env:computername\logroot\")

In short, the -replace operator is same as Regex.Replace (the particular overload linked above), but in general Replace() can be instance or static method that can be doing anything completely different from -replace

这篇关于在Powershell中.replace和-replace有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆