寻找 RexEx 替换字符串中的字符串

looking for RexEx to replace a string within a string

我必须用 Powershell 替换文本文件中的字符串。文本文件包含以下内容:

app.framework.locale=de_DE
app.gf.data.profile=somevalues,somevalues[,...]
app.gf.data.profile.path=C:\somepath\somesubpath
app.basket.currencies=currencies

我想设置配置文件和profile.path。因此,无论“=”后面的字符串有多长,“=”后面的所有内容都应该被替换。

我正在读取文件、替换字符串并使用这些命令写回文件:

更改配置文件:

(Get-Content $TXT_FILE ).Replace('app.gf.data.profile=default,',"app.gf.data.profile=default,$Man") | Out-File $TXT_FILE -Encoding ASCII

更改配置文件路径:

(Get-Content $TXT_FILE ).Replace('app.gf.data.profile.path=',"app.gf.data.profile.path=$Path") | Out-File $TXT_FILE -Encoding ASCII

如您所见,我的替换脚本不正确,“=”后面的其余部分将保留。我想我需要一个正则表达式或某种通配符来满足我的需要。

您需要使用

(Get-Content $TXT_FILE) `
  -replace '^(app\.gf\.data\.profile=).*', "`,$Man" `
  -replace '^(app\.gf\.data\.profile\.path=).*', "`$Path" | `
Out-File $TXT_FILE -Encoding ASCII

这里,-replace用于启用正则表达式替换,两个正则表达式遵循类似的逻辑:

  • ^ - 匹配行首
  • (app\.gf\.data\.profile=) - 将文字字符串(正则表达式中的文字点必须转义)捕获到第 1 组(</code> 或 <code>
  • .* - 匹配该行的其余部分。

</code> 在第二种情况下使用,因为变量 <code>$Path 紧跟在反向引用之后,如果它以数字开头,替换将不会像预期的那样。