PowerShell中如何删除变量中指定单词之前的所有文本?
删除指定单词之前的所有文本(PowerShell)
要删除目标单词(比如elephant)之前的所有内容,同样可以用PowerShell的-replace结合正则表达式实现,分两种场景处理:
保留目标单词:使用正向预查仅删除单词前的内容,不包含单词本身,同时通过单行模式修饰符处理跨行内容:
$Trimthis -replace '(?s)^.*?(?=elephant)'正则说明:
(?s):单行模式,让.可以匹配换行符,确保跨行文本也能被处理^:匹配字符串开头.*?:非贪婪模式匹配任意字符,直到遇到目标单词(?=elephant):正向预查,定位到目标单词的起始位置,不包含单词本身
同时删除目标单词:如果不需要保留
elephant,直接匹配到单词结尾即可:$Trimthis -replace '(?s)^.*?elephant'
测试示例
$Trimthis = @" Some random text before the elephant and some text after "@ # 保留elephant的结果 $Trimthis -replace '(?s)^.*?(?=elephant)' # 输出: # elephant # and some text after # 删除elephant的结果 $Trimthis -replace '(?s)^.*?elephant' # 输出: # # and some text after
内容的提问来源于stack exchange,提问作者Gavin Eldred
相关产品推荐
相关产品推荐

