首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Powershell使用定义列表中的单词清理字符串数据

Powershell使用定义列表中的单词清理字符串数据
EN

Stack Overflow用户
提问于 2021-12-25 06:33:38
回答 1查看 57关注 0票数 0
代码语言:javascript
复制
$ignoreList =  @("muzi","puzi")

$data = "
blabla aa 11
blabla bb 22
muzi aa 20
muzi bb aa
aaa aa 41
blabla aa 20
puzi aa 11
puzi bb 32
puzi cc 44"

我需要创建新的数据,它保存除忽略列表中的所有数据外的所有数据。

代码语言:javascript
复制
#i can iterate the list and run a loop, get $str to be the item in the list and 
#and then save each time
$data | where-object {$_ -notlike $str}

我觉得有比每次迭代abd savubg列表更好的选择

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-25 15:53:51

-like当时只能处理一个模式(通配符表达式)。

要在单个操作中匹配多个模式,有两个选项:

  • 使用regex-based -notmatch 运算符和交替表达式,该表达式要求您用[regex]::Escape()来转义忽略的单词,以便逐字使用它们作为正则表达式的一部分(对于特定的搜索术语来说,这不是绝对必要的,因此在这种简单的情况下,您可以使用'^(?:{0})' -f ($ignoreList -join '|'));正则表达式的使用还允许您断言必须在每个字符串的开头找到每个忽略单词(^):
代码语言:javascript
复制
$ignoreList =  @("muzi","puzi")

# Create an *array* of sample lines.
$data = @'
blabla aa 11
blabla bb 22
muzi aa 20
muzi bb aa
aaa aa 41
blabla aa 20
puzi aa 11
puzi bb 32
puzi cc 44"
'@ -split '\r?\n'

# The programmatically created regex results in:
#    '^(?:muzi|puzi)'
# The ?: part isn't strictly necessary, but makes the (...) group
# non-capturing, which prevents unnecessary work.
$data -notmatch ('^(?:{0})' -f ($ignoreList.ForEach({ [regex]::Escape($_) }) -join '|'))
  • 使用带有多个模式的选择字符串 cmdlet (尽管您也可以使用一个带有替换的模式),如果添加-SimpleMatch,这可能是字面搜索术语。由于使用管道,这种方法更简单,但速度更慢:
代码语言:javascript
复制
# Note the need to use (...).Line to extract the matching strings.
# In PowerShell (Core) 7+ you could use -Raw instead.
($data | Select-String -Pattern $ignoreList -SimpleMatch -NotMatch).Line
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70478355

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档