PowerShell常用正则表达式和语法参考

本文介绍PowerShell中的正则表达式,各种不同的字符代表不同的含义,包括占位符PlaceHolder、量词Quantifier和边界字符。

下面列举PowerShell的正则表达式中可能出现的字符,以及它们表示的含义。

字符串的匹配符(占位符PlaceHolder)

. 这是一个点儿,表示换行符之外的任意一个字符(Any character except newline (Equivalent: [^n]))
[^abc] 指定的字符(abc)之外的任意一个字符,可以把abc换成其它字符组。(All characters except the ones specified)
[^a-z] 任意一个非小写字母的字符(All characters except those in the region specified)
[abc] 指定的字符集中的任意一个,即abc中的任意一个(One of the characters)
[a-z] 指定的字符范围中的任意一个,即任意一个小写字母。One of the characters in the region
a 响呤(Bell (ASCII 7))
c Any character allowed in XML names
cA-cZ Control+A to Control+Z, ASCII 1 to ASCII 26
d 任意一个数字,等同于[0-9](Any number (Equivalent: [0-9]))
D 任意一个非数字。Any non-number
e ESC键(Escape (ASCII 27))
f Form Feed, (ASCII 12)
n 换行Line break
r 回车Carriage return
s 任意一个空白键(空白键如tab,换行)Any whitespace (space, tab, new line)
S 任意一个非空白字符(Any non-whitespace)
t tab键
w 字母,数字和下划线(Letter, number or underline)
W w的补集(Non-letter, number, or underline)

匹配次数(量词Quantifier)

* 出现零次、1次、多次(Any (no occurrence, once, many times))
? 出现零次、1次(No occurrence or one occurrence)
{n,} 出现至少n次(At least n occurrences)
{n,m} 出现至少n次,最多m次(At least n occurrences, maximum m occurrences)
{n} 出现n次(Exactly n occurrences)
+ 出现1次、多次(One or many occurrences)

所有的匹配次数的符号,默认情况下都是贪婪的,即它将最大长度的进行匹配。如果想要得到最短的匹配,那就要在上面这组符号之后加一个问号(?)。

匹配边界

$ 字符串结束(End of text)
^ 字符串开始(Start of text)
b Word boundary
B No word boundary
G After last match (no overlaps)

关于PowerShell正则表达式参考,本文就介绍这么多,希望对您有所帮助,谢谢!