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

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

问题描述

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

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:computernamelogroot")


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

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

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.

谢谢

推荐答案

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

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:computernamelogroot")

简而言之,-replace 运算符与 Regex.Replace(上面链接的特定重载)相同,但一般来说 Replace() 可以是实例或静态方法,可以做与 -replace

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天全站免登陆