24

.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) メソッド。

ありがとうございました

4

2 に答える 2

27

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

于 2012-04-17T04:49:53.503 に答える
18

それらは同じものではありません。.ReplaceSystem.String または という名前のインスタンス メソッドを持つその他の型の .NET メソッドReplaceです。 -replace正規表現を使用する PowerShell 演算子です。実行して、オペレーターman about_operatorsに関する詳細情報を表示します。-replace

于 2012-04-17T02:57:34.070 に答える