我有以下
$file_input = "cube1_server1_partial.xml"
$CUBEName = [io.path]::GetFileNameWithoutExtension($file_input).ToUpper() -replace "_partial" #strips extension from $file_input
结果是: cube1_server1
现在我有了其他文件名,例如
cube1_server1_full.xml
我想要一个全面的替代产品,不必一定要对后缀进行硬编码,因此 -replace "_partial"
它应该是-replace "_*"
从字符串末尾开始的
我应该如何进行全面更换?也许与正则表达式?
如果_
要从字符串中删除最后一个及其后的所有内容,则有两种选择。
使用String.LastIndexOf()
和String.Remove()
:
$string = 'cube1_server1_partial'
$last_index = $string.LastIndexOf('_')
if($last_index -ne -1){
$string = $string.Remove($last_index)
}
或者,您可以将-replace
regex运算符与更具描述性的模式一起使用:
$string = 'cube1_server1_partial'
$string -replace '(?<=.+)_[^_]*$'
上例中的正则表达式包括:
(?<= # positive look-behind assertion
.+ # for 1 or more characters
)
_ # a literal underscore
[^_]* # any character that's NOT an underscore, 0 or more times
$ # followed by end of string
如果仅_
出现在位置0,则回溯确保您不会以空字符串结尾。_partial
会照原样返回。对于非正则表达式方法,等效方法是检查$last_index -gt 0
而不是-ne -1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句