PowerShell 中的正则表达式PowerShell 中的正则表达式PowerShell 中的正则表达式PowerShell 中的正则表达式
  • 文章
  • 正则表达式
    • 工具
  • 登录
找到的结果: {phrase} (显示: {results_count} 共: {results_count_total})
显示: {results_count} 共: {results_count_total}

加载更多搜索结果...

搜索范围
模糊匹配
搜索标题
搜索内容
发表 admin at 2024年3月5日
类别
  • 正则表达式
标签
PowerShell 中的正则表达式
  • 简
  • 繁
  • En
关于正则表达式 » 正则表达式工具和实用程序 » PowerShell 中的正则表达式

正则表达式工具
grep
语言和函数库
Boost
Delphi
GNU (Linux)
Groovy
Java
JavaScript
.NET
PCRE (C/C++)
PCRE2 (C/C++)
Perl
PHP
POSIX
PowerShell
Python
R
Ruby
std::regex
Tcl
VBScript
Visual Basic 6
wxWidgets
XML Schema
Xojo
XQuery 和 XPath
XRegExp
数据库
MySQL
Oracle
PostgreSQL
更多内容
简介
正则表达式快速入门
正则表达式教程
替换字符串教程
应用程序和语言
正则表达式范例
正则表达式参考
替换字符串参考

PowerShell 中的正则表达式

PowerShell 是 Microsoft 的编程语言,主要设计用于系统管理。PowerShell 创建在 .NET 之上,因此 PowerShell 程序员也可以使用 .NET 出色的正则表达式支持。

以下讨论同样适用于 Windows PowerShell 1.0 到 5.1、PowerShell Core 6 和 PowerShell 7。自 .NET 2.0 之后,.NET 或 .NET Core 中的正则表达式语法并未有任何变更。PowerShell 1.0 在 .NET 2.0 之后发布。因此,所有版本的 PowerShell 都使用相同的正则表达式语法。Windows PowerShell 2.0 和 5.0 添加了一些功能,让分割字符串和调用其他 Regex() 构造函数变得更容易。除此之外,在使用正则表达式方面,所有 PowerShell 版本之间没有任何差异。

PowerShell -Match 和 -Replace 营运子

使用 -match 营运子,您可以快速检查正则表达式是否与字符串的一部分相符。例如,'test' -match '\w' 会传回 true,因为 \w 与 test 中的 t 相符。

作为副作用,-match 营运子会设置一个称为 $matches 的特殊变量。这是一个关联数组,用于保存整体正则表达式相符项和所有捕获组相符项。$matches[0] 会提供您整体正则表达式相符项,$matches[1] 会提供第一个捕获组,而 $matches['name'] 会提供由命名组「name」相符的文本。

-replace 营运子使用正则表达式在字符串中进行搜索和取代。例如,'test' -replace '\w', '$&$&' 会传回 'tteesstt'。正则表达式 \w 会相符一个字母。取代文本会使用 $& 两次重新插入正则表达式相符项。必须指定取代文本参数,并且正则表达式和取代项必须以逗号分隔。如果您要将正则表达式相符项取代为空白,请传递一个空白字符串作为取代项。

传统上,正则表达式缺省会区分大小写。.NET 架构也是如此。不过,PowerShell 中并非如此。-match 和 -replace 不区分大小写,-imatch 和 -ireplace 也是如此。对于区分大小写的相符项,请使用 -cmatch 和 -creplace。我建议您始终使用「i」或「c」前缀,以避免对大小写敏感性感到困惑。

操作符不提供传递 .NET 的 RegexOptions 枚举选项的方法。请改用正则表达式中的模式修改器。例如 (?m)^test$ 等同于将 RegexOptions.MultiLine 传递给 Regex() 构造函数,并使用 ^test$。模式修改器优先于外部设置的正则表达式选项。-cmatch '(?i)test' 不分大小写,而 -imatch '(?-i)test' 则区分大小写。模式修改器会覆写 -match 操作符的不区分大小写偏好设置。

PowerShell -Split 操作符

PowerShell 2.0(随 Windows 7 SP1 推出)添加了 -split 操作符。它允许您沿着正则表达式比对来分割字符串。例如 $subject -split "\W+" 会沿着非字符字符来分割主旨字符串,因此会传回字符串中所有字词的数组。

替换文本作为字面字符串

-replace 操作符支持与 .NET 中的 Regex.Replace() 函数相同的替换文本占位符。$& 是整体正则表达式比对,$1 是由第一个捕获组比对的文本,而 ${name} 是由命名组「name」比对的文本。

但在 PowerShell 中,有一个额外的注意事项:双引号字符串使用美元语法进行变量内插。变量内插会在 Regex.Replace() 函数(-replace 在内部使用)解析替换文本之前完成。与 Perl 不同,$1 在 PowerShell 中并非神奇变量。该语法仅在替换文本中有效。-replace 操作符也不会设置 $matches 变量。因此 'test' -replace '(\w)(\w)', "$2$1"(双引号替换)会传回空字符串(假设您未在先前的 PowerShell 代码中设置变量 $1 和 $2)。由于变量内插,Replace() 函数永远不会看到 $2$1。若要让 Replace() 函数取代其占位符,请使用 'test' -replace '(\w)(\w)', '$2$1'(单引号替换)或 'test' -replace '(\w)(\w)', "`$2`$1"(美元符号以反引号转义),以确保 $2$1 会以字面形式传递给 Regex.Replace()。

使用 System.Text.RegularExpressions.Regex 类别

若要使用 PowerShell 的所有 .NET 正规表达式处理功能,请通过实例化 System.Text.RegularExpressions.Regex 类别来创建正规表达式对象。如果您想要使用 Regex() 构造函数,它会将字符串视为唯一参数,而正规表达式则会编译,PowerShell 会提供一个便利的捷径。 $regex = [regex] '\W+' 编译正规表达式 \W+(与一个或多个非字符元匹配)并将结果保存在变量 $regex 中。您现在可以在 $regex 对象上调用 Regex 类别的所有方法。

在 PowerShell 5.0 及更新版本中,您可以在类别名称上调用另一个 Regex() 构造函数

using namespace System.Text.RegularExpressions
$regex = [Regex]::new('^test$', [RegexOptions]::MultiLine)

在旧版本的 PowerShell 中,您必须使用 PowerShell 的 new-object cmdlet。例如,若要设置 RegexOptions.MultiLine 旗标,您需要这行代码

$regex = new-object System.Text.RegularExpressions.Regex ('^test$',
         [System.Text.RegularExpressions.RegexOptions]::MultiLine)

在任何版本的 PowerShell 中,正规表达式内的 模式修改器 都可以提供更简短的解决方案

$regex = [regex] '(?m)^test$'

模式修改器也可以与 -match、-replace 和 -split 营运子搭配使用。

PowerShell 中的正規表示式
  • 简
  • 繁
  • En
關於正規表示式 » 正規表示式工具和實用程式 » PowerShell 中的正規表示式

正規表示式工具
grep
語言和函式庫
Boost
Delphi
GNU (Linux)
Groovy
Java
JavaScript
.NET
PCRE (C/C++)
PCRE2 (C/C++)
Perl
PHP
POSIX
PowerShell
Python
R
Ruby
std::regex
Tcl
VBScript
Visual Basic 6
wxWidgets
XML Schema
Xojo
XQuery 和 XPath
XRegExp
資料庫
MySQL
Oracle
PostgreSQL
本網站的更多資訊
簡介
正規表示式快速入門
正規表示式教學
替換字串教學
應用程式和語言
正規表示式範例
正規表示式參考
替換字串參考

PowerShell 中的正規表示式

PowerShell 是 Microsoft 的程式語言,主要設計用於系統管理。PowerShell 建立在 .NET 之上,因此 PowerShell 程式設計師也可以使用 .NET 出色的正規表示式支援。

以下討論同樣適用於 Windows PowerShell 1.0 到 5.1、PowerShell Core 6 和 PowerShell 7。自 .NET 2.0 之後,.NET 或 .NET Core 中的正規表示式語法並未有任何變更。PowerShell 1.0 在 .NET 2.0 之後釋出。因此,所有版本的 PowerShell 都使用相同的正規表示式語法。Windows PowerShell 2.0 和 5.0 新增了一些功能,讓分割字串和呼叫其他 Regex() 建構函式變得更容易。除此之外,在使用正規表示式方面,所有 PowerShell 版本之間沒有任何差異。

PowerShell -Match 和 -Replace 營運子

使用 -match 營運子,您可以快速檢查正規表示式是否與字串的一部分相符。例如,'test' -match '\w' 會傳回 true,因為 \w 與 test 中的 t 相符。

作為副作用,-match 營運子會設定一個稱為 $matches 的特殊變數。這是一個關聯陣列,用於儲存整體正規表示式相符項和所有擷取群組相符項。$matches[0] 會提供您整體正規表示式相符項,$matches[1] 會提供第一個擷取群組,而 $matches['name'] 會提供由命名群組「name」相符的文字。

-replace 營運子使用正規表示式在字串中進行搜尋和取代。例如,'test' -replace '\w', '$&$&' 會傳回 'tteesstt'。正規表示式 \w 會相符一個字母。取代文字會使用 $& 兩次重新插入正規表示式相符項。必須指定取代文字參數,並且正規表示式和取代項必須以逗號分隔。如果您要將正規表示式相符項取代為空白,請傳遞一個空白字串作為取代項。

傳統上,正規表示式預設會區分大小寫。.NET 架構也是如此。不過,PowerShell 中並非如此。-match 和 -replace 不區分大小寫,-imatch 和 -ireplace 也是如此。對於區分大小寫的相符項,請使用 -cmatch 和 -creplace。我建議您始終使用「i」或「c」前綴,以避免對大小寫敏感性感到困惑。

運算子不提供傳遞 .NET 的 RegexOptions 列舉選項的方法。請改用正規表示式中的模式修改器。例如 (?m)^test$ 等同於將 RegexOptions.MultiLine 傳遞給 Regex() 建構函式,並使用 ^test$。模式修改器優先於外部設定的正規表示式選項。-cmatch '(?i)test' 不分大小寫,而 -imatch '(?-i)test' 則區分大小寫。模式修改器會覆寫 -match 運算子的不區分大小寫偏好設定。

PowerShell -Split 運算子

PowerShell 2.0(隨 Windows 7 SP1 推出)新增了 -split 運算子。它允許您沿著正規表示式比對來分割字串。例如 $subject -split "\W+" 會沿著非字元字元來分割主旨字串,因此會傳回字串中所有字詞的陣列。

替換文字作為字面字串

-replace 運算子支援與 .NET 中的 Regex.Replace() 函式相同的替換文字佔位符。$& 是整體正規表示式比對,$1 是由第一個擷取群組比對的文字,而 ${name} 是由命名群組「name」比對的文字。

但在 PowerShell 中,有一個額外的注意事項:雙引號字串使用美元語法進行變數內插。變數內插會在 Regex.Replace() 函式(-replace 在內部使用)解析替換文字之前完成。與 Perl 不同,$1 在 PowerShell 中並非神奇變數。該語法僅在替換文字中有效。-replace 運算子也不會設定 $matches 變數。因此 'test' -replace '(\w)(\w)', "$2$1"(雙引號替換)會傳回空字串(假設您未在先前的 PowerShell 程式碼中設定變數 $1 和 $2)。由於變數內插,Replace() 函式永遠不會看到 $2$1。若要讓 Replace() 函式取代其佔位符,請使用 'test' -replace '(\w)(\w)', '$2$1'(單引號替換)或 'test' -replace '(\w)(\w)', "`$2`$1"(美元符號以反引號跳脫),以確保 $2$1 會以字面形式傳遞給 Regex.Replace()。

使用 System.Text.RegularExpressions.Regex 類別

若要使用 PowerShell 的所有 .NET 正規運算式處理功能,請透過實例化 System.Text.RegularExpressions.Regex 類別來建立正規運算式物件。如果您想要使用 Regex() 建構函式,它會將字串視為唯一參數,而正規運算式則會編譯,PowerShell 會提供一個便利的捷徑。 $regex = [regex] '\W+' 編譯正規運算式 \W+(與一個或多個非字元元匹配)並將結果儲存在變數 $regex 中。您現在可以在 $regex 物件上呼叫 Regex 類別的所有方法。

在 PowerShell 5.0 及更新版本中,您可以在類別名稱上呼叫另一個 Regex() 建構函式

using namespace System.Text.RegularExpressions
$regex = [Regex]::new('^test$', [RegexOptions]::MultiLine)

在舊版本的 PowerShell 中,您必須使用 PowerShell 的 new-object cmdlet。例如,若要設定 RegexOptions.MultiLine 旗標,您需要這行程式碼

$regex = new-object System.Text.RegularExpressions.Regex ('^test$',
         [System.Text.RegularExpressions.RegexOptions]::MultiLine)

在任何版本的 PowerShell 中,正規運算式內的 模式修改器 都可以提供更簡短的解決方案

$regex = [regex] '(?m)^test$'

模式修改器也可以與 -match、-replace 和 -split 營運子搭配使用。

Regular Expressions with PowerShell
  • 简
  • 繁
  • En
About Regular Expressions » Tools and Utilities for Regular Expressions » Regular Expressions with PowerShell

Regex Tools
grep
Languages & Libraries
Boost
Delphi
GNU (Linux)
Groovy
Java
JavaScript
.NET
PCRE (C/C++)
PCRE2 (C/C++)
Perl
PHP
POSIX
PowerShell
Python
R
Ruby
std::regex
Tcl
VBScript
Visual Basic 6
wxWidgets
XML Schema
Xojo
XQuery & XPath
XRegExp
Databases
MySQL
Oracle
PostgreSQL
More on This Site
Introduction
Regular Expressions Quick Start
Regular Expressions Tutorial
Replacement Strings Tutorial
Applications and Languages
Regular Expressions Examples
Regular Expressions Reference
Replacement Strings Reference

Regular Expressions with PowerShell

PowerShell is a programming language from Microsoft that is primarily designed for system administration. PowerShell is built on top of .NET so .NET’s excellent regular expression support is also available to PowerShell programmers.

The discussion below applies equally to Windows PowerShell 1.0 to 5.1, PowerShell Core 6, and PowerShell 7. There haven’t been any changes to the regex syntax in .NET or in .NET Core since .NET 2.0. PowerShell 1.0 was released after .NET 2.0. So all versions of PowerShell use the same regex syntax. Windows PowerShell 2.0 and 5.0 added some features that make it easier to split strings and invoke other Regex() constructors. Other than that, there are no differences between any of the PowerShell versions regarding the use of regular expressions.

PowerShell -Match and -Replace Operators

With the -match operator, you can quickly check if a regular expression matches part of a string. E.g. 'test' -match '\w' returns true, because \w matches t in test.

As a side effect, the -match operator sets a special variable called $matches. This is an associative array that holds the overall regex match and all capturing group matches. $matches[0] gives you the overall regex match, $matches[1] the first capturing group, and $matches['name'] the text matched by the named group “name”.

The -replace operator uses a regular expression to search-and-replace through a string. E.g. 'test' -replace '\w', '$&$&' returns 'tteesstt'. The regex \w matches one letter. The replacement text re-inserts the regex match twice using $&. The replacement text parameter must be specified, and the regex and replacement must be separated by a comma. If you want to replace the regex matches with nothing, pass an empty string as the replacement.

Traditionally, regular expressions are case sensitive by default. This is true for the .NET framework too. However, it is not true in PowerShell. -match and -replace are case insensitive, as are -imatch and -ireplace. For case sensitive matching, use -cmatch and -creplace. I recommend that you always use the “i” or “c” prefix to avoid confusion regarding case sensitivity.

The operators do not provide a way to pass options from .NET’s RegexOptions enumeration. Instead, use mode modifiers in the regular expression. E.g. (?m)^test$ is the same as using ^test$ with RegexOptions.MultiLine passed to the Regex() constructor. Mode modifiers take precedence over options set externally to the regex. -cmatch '(?i)test' is case insensitive, while -imatch '(?-i)test' is case sensitive. The mode modifier overrides the case insensitivity preference of the -match operator.

PowerShell -Split Operator

PowerShell 2.0, introduced with Windows 7 SP1, added the -split operator. It allows you to split a string along regex matches. E.g. $subject -split "\W+" splits the subject string along non-word characters, thus returning an array of all the words in the string.

Replacement Text as a Literal String

The -replace operator supports the same replacement text placeholders as the Regex.Replace() function in .NET. $& is the overall regex match, $1 is the text matched by the first capturing group, and ${name} is the text matched by the named group “name”.

But with PowerShell, there’s an extra caveat: double-quoted strings use the dollar syntax for variable interpolation. Variable interpolation is done before the Regex.Replace() function (which -replace uses internally) parses the replacement text. Unlike Perl, $1 is not a magical variable in PowerShell. That syntax only works in the replacement text. The -replace operator does not set the $matches variable either. The effect is that 'test' -replace '(\w)(\w)', "$2$1" (double-quoted replacement) returns the empty string (assuming you did not set the variables $1 and $2 in preceding PowerShell code). Due to variable interpolation, the Replace() function never sees $2$1. To allow the Replace() function to substitute its placeholders, use 'test' -replace '(\w)(\w)', '$2$1' (single-quoted replacement) or 'test' -replace '(\w)(\w)', "`$2`$1" (dollars escaped with backticks) to make sure $2$1 is passed literally to Regex.Replace().

Using The System.Text.RegularExpressions.Regex Class

To use all of .NET’s regex processing functionality with PowerShell, create a regular expression object by instantiating the System.Text.RegularExpressions.Regex class. PowerShell provides a handy shortcut if you want to use the Regex() constructor that takes a string with your regular expression as the only parameter. $regex = [regex] '\W+' compiles the regular expression \W+ (which matches one or more non-word characters) and stores the result in the variable $regex. You can now call all the methods of the Regex class on your $regex object.

In PowerShell 5.0 and later you can invoke another Regex() constructor on the class name:

using namespace System.Text.RegularExpressions
$regex = [Regex]::new('^test$', [RegexOptions]::MultiLine)

In older versions of PowerShell, you have to resort to PowerShell’s new-object cmdlet. To set the flag RegexOptions.MultiLine, for example, you’d need this line of code:

$regex = new-object System.Text.RegularExpressions.Regex ('^test$',
         [System.Text.RegularExpressions.RegexOptions]::MultiLine)

In any version of PowerShell, mode modifiers inside the regex can provide a shorter solution:

$regex = [regex] '(?m)^test$'

Mode modifiers also work with the -match, -replace, and -split operators.

©2015-2025 艾丽卡 support@alaica.com