Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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: 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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
545 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...