regex - 从文本字符串中删除特定单词?
问题描述
所以说你有一个变量字符串,如:"Report to Sam.Smith"
什么是你删除单词' Report
'和' to
'只Sam.Smith
使用Powershell的最佳方法?
解决方案
您必须使用-replace:
$string = "Report to Sam.Smith"
$string = $string -replace "Report to ",""
$string # Output --> "Sam.Smith"
或者像这样:
$string = "Report to Sam.Smith"
$string = $string.replace("Report to ","")
$string # Output --> "Sam.Smith"
但是,如果您需要使用正则表达式,因为字符串的单词可能会有所不同,那么您必须重新考虑问题。
您不会希望擦除字符串的一部分,而是要从中提取一些内容。
在你的情况下,我认为你正在寻找一个使用 name.lastname 格式的用户名,这很容易捕获:
$string = "Report to Sam.Smith"
$string -match "\s(\w*\.\w*)"
$Matches[1] # Output --> Sam.Smith
使用-match将返回 True / False。
如果它确实返回 True,将创建一个名为 $Matches 的数组。它将在索引 0 ($Matches[0]) 上包含与正则表达式匹配的整个字符串。
大于 0 的每个其他索引将包含从称为“捕获组”的正则表达式括号中捕获的文本。
我强烈建议使用if 语句,因为如果您的正则表达式返回 false,则数组 $Matches 将不存在:
$string = "Report to Sam.Smith"
if($string -match "\s(\w*\.\w*)") {
$Matches[1] # Output --> Sam.Smith
}
推荐阅读
- python - 如何将文本文件中的行附加到python 3x中的多个列表
- sql - 在 Postgres 中使用表值参数调用函数
- jquery - 禁用/启用提交按钮的 jQuery 自定义插件
- ios - Swift 分段控制和 UITableView
- xml - IBMi (XMLTABLE) xml 中的 XML 解析问题
- php - FatalErrorException 在 null 上调用成员函数 except()
- java - ElasticSearch Java 高级 REST 客户端:过滤文档和/或查询
- typescript - 为什么在使用 Array.isArray 时类型推断会丢失?
- excel - 使用 VBA,您可以输入一个引用另一个具有动态名称的工作簿的公式吗?
- eclipse - 在 PHP Eclipse 上安装 egit 但出现错误