我正在尝试从Powershell对多个word文档进行查找替换。我想要替换的字符串格式为:
@XXXXXXX
X是字母数字字符(这是合并字段在我们系统中的样子)。
我用作查找文本的字符串是:
"\@*"
我假设是以@开头,后跟多个字符。反斜杠用作Word中通配符@的转义字符。
这只是替换文档中的@符号,忽略后面的字符。
如何设置搜索词以尊重@及其后的字符并将其全部替换?
目前形式的完整脚本是:
$list = Get-ChildItem "H:\Quick Report Replace" -Include *.xml -recurse
$objWord = New-Object -ComObject word.application
$objWord.Visible = $False
foreach ($foo in $list) {
$objDoc = $objWord.Documents.Open("$foo")
$objSelection = $objDoc.Selection
$findtext= "\@*"
$ReplaceText = "_______________"
$ReplaceAll = 2
$FindContinue = 1
$MatchFuzzy = $False
$MatchCase = $False
$MatchPhrase = $false
$MatchWholeWord = $False
$MatchWildcards = $True
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $FindContinue
$Format = $False
$objSelection.Find.execute(
$FindText,
$MatchCase,
$MatchWholeWord,
$MatchWildcards,
$MatchSoundsLike,
$MatchAllWordForms,
$Forward,
$Wrap,
$Format,
$ReplaceText,
$ReplaceAll
)
If ($objSelection.Find.Found)
{
Write-Host("The search text was found.") } Else {
Write-Host("The search text was not found.") }
$objDoc.close()
}
答案 0 :(得分:1)
Word会执行非贪婪的匹配,因此您的表达\@*
只会匹配文字@
后的最短个字符数。由于在*
通配符之后没有任何内容可以充当锚点,因此您案例中最短的字符数始终为零,因此您只能匹配@
字符本身
要匹配后续的字母数字字符,您需要将表达式的结尾锚定在某处,例如在单词边界处:
\@*>