2014-05-07 30 views
0

我有一定的琴絃低於經常在PowerShell中替換字符串表達式

PS C:\Users> $S1="PS CUT (ZIP ONLY), ALWAYS chose for MARTIO" 
PS C:\Users> $s2="ZINO-IAS CUT" 
PS C:\Users> $s3="ZINO-IPS CUT 2" 
PS C:\Users> $s4="ZINO-IAS CUT4" 
PS C:\Users> $s5="ZINO-IPS" 

我想從這個詞代替上述字符串CUT本身給出如下

PS 
ZINO-IAS 
ZINO-IPS2 
ZINO-IAS4 
ZINO-IPS 

Plase沒有給出如果後面有一個數字CUT我們並沒有刪除它。

我嘗試下面的代碼,但它不工作

PS C:\Users> $s5 -replace "CUT\s*\w*","" 

回答

1

您所需要的正則表達式是:

"\s*CUT\s*(\d+)?.*","`$1" 

它檢查後CUT任何空間,配備可選的數並使用它作爲替代(由$ 1表示)。如果該號碼不存在,則用空字符串替換整個匹配。

結果:

[PS]> $s1 -replace "\s*CUT\s*(\d+)?.*","`$1" 
PS 
[PS]> $s2 -replace "\s*CUT\s*(\d+)?.*","`$1" 
ZINO-IAS 
[PS]> $s3 -replace "\s*CUT\s*(\d+)?.*","`$1" 
ZINO-IPS2 
[PS]> $s4 -replace "\s*CUT\s*(\d+)?.*","`$1" 
ZINO-IAS4 
[PS]> $s5 -replace "\s*CUT\s*(\d+)?.*","`$1" 
ZINO-IPS