Regular Expressions

本文深入探讨了正则表达式的使用方法,包括匹配字符、范围、特殊字符、删除和替换文本等内容,并通过实例展示了如何在实际场景中应用正则表达式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Regular Expressions

Use -match , -notmatch or -replace to identify string patterns using regular expression characters:

Match exact characters anywhere in the original string:
PS C:> "Ziggy stardust" -match "iggy"

A period . will match a single character:
PS C:> "cat" -match "c.t"
PS C:> "Ziggy stardust" -match "s..rdust"

Match any (at least one) of the characters - place the options in square brackets [ ]
PS C:> "Ziggy stardust" -match "Z[xyi]ggy"

Match a range (at least one) of characters in a contiguous range [n-m]
PS C:> "Ziggy stardust" -match "Zigg[x-z] Star"

Match any but these, a caret (^) will match any character except those in brackets
PS C:> "Ziggy stardust" -match "Zigg[^abc] Star"

Remove the beginning characters: ^
PS C:> "no alarms and no surprises" -replace '^no',''
alarms and no surprises

Replace the end characters: $
PS C:> "There must be some way out of here said the joker to the joker" -replace 'joker$','thief'
There must be some way out of here said the joker to the thief

Match zero or more instances of the preceding character: *
PS C:> "Ziggy stardust" -match "g*"

Match zero or one instance of the preceding character: ?
PS C:> "Ziggy stardust" -match "g?"

Match the character that follows as an escaped character
PS C:> "Ziggy$" -match "Ziggy\$"

Match any character in a character class: \p{name}
Supported names are Unicode groups and block ranges for example, Ll (Letter, Uppercase), Nd (Number, Decimal Digit), Z (All separators), IsGreek, IsBoxDrawing.

PS C:> "ZiGGY Stardust" -match "\p{Ll}+"

Match text not included in groups and block ranges: \P{name} .
PS C:> 1234 -match "\P{Ll}+"

Match any word character: \w This is equivalent to [a-zA-Z_0-9]
PS C:> "Ziggy stardust" -match "\w+"

Match any nonword character \W This is equivalent to [^a-zA-Z_0-9]
PS C:> "Ziggy stardust" -match " \W+"

Match any white-space: \s This is equivalent to [ \f\n\r\t\v]
PS C:> "Ziggy stardust" -match "\s+"

Match any non-white-space: \S This is equivalent to [^ \f\n\r\t\v]
PS C:> "Ziggy stardust" -match "\S+"

Match any decimal digit: \d This is equivalent to \p{Nd} for Unicode and [0-9] for non-Unicode
PS C:> 12345 -match "\d+"

Match any nondigit: \D This is equivalent to \P{Nd} for Unicode and [^0-9] for non-Unicode
PS C:> "Ziggy stardust" -match "\D+"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值