Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Powershell中使用regex替换单引号中的字符串_Regex_Powershell - Fatal编程技术网

在Powershell中使用regex替换单引号中的字符串

在Powershell中使用regex替换单引号中的字符串,regex,powershell,Regex,Powershell,考虑到这个文件 AppConfig = { version: '4.0.0', clientId: "guid", httpProxy: 'rest', restUrl: "http://url.contoso.com/v1/", conferences: ["lync", "hangouts", "webex"], // "lync", "hangouts", "webex" dataRefreshInterval: 60 //seco

考虑到这个文件

AppConfig = {
    version: '4.0.0',
    clientId: "guid",
    httpProxy: 'rest',
    restUrl: "http://url.contoso.com/v1/",

    conferences: ["lync", "hangouts", "webex"],    // "lync", "hangouts", "webex"

    dataRefreshInterval: 60 //seconds
} 
我想用另一个字符串替换单引号内的字符串。我想更改特定属性的值(在我的示例中为
版本

$content=获取内容$VersionFile
对于($i=0;$i-lt$content.Count;$i++)
{
如果($content[$i]-类似“*版本:”)
{
$content[$i]=$content[$i]-creplace,
}      
}

如果您只想替换版本引号中的文本,请执行以下操作:

$content = Get-Content $VersionFile
$replacement = <ReplaceWith>
$content = $content -creplace "version: '[^']*'","version: '$replacement'"
$content=获取内容$VersionFile
$replacement=
$content=$content-creplace“版本:'[^']*',“版本:'$replacement'”

它将用文本中的
替换
4.0.0
,如果您只想替换版本引号中的文本,可以执行以下操作:

$content = Get-Content $VersionFile
$replacement = <ReplaceWith>
$content = $content -creplace "version: '[^']*'","version: '$replacement'"
$content=获取内容$VersionFile
$replacement=
$content=$content-creplace“版本:'[^']*',“版本:'$replacement'”
它将用文本中的
替换
4.0.0
,您可以尝试以下操作:

$version = "x.x.x.x"
$content = Get-Content $VersionFile
$content -replace "version: '(.*)'","version: '$version'"
您可以尝试以下方法:

$version = "x.x.x.x"
$content = Get-Content $VersionFile
$content -replace "version: '(.*)'","version: '$version'"

@流行病:如果你想替换单引号内的任何字符串,你必须对每个替换都这样做,因为我猜每个替换的文本都不一样item@pandemic:如果要替换单引号内的任何字符串,则每次替换都必须执行此操作,因为我猜每个项目的替换文本都不一样,所以需要将
*
设置为惰性,否则它将无法工作。您的正则表达式将从
version
匹配到
'rest',
这里您所说的“懒惰”是什么意思?我的代码可以工作,但我可以改进我的正则表达式;-)默认情况下,
*
是贪婪的。这意味着它将匹配尽可能多的字符。在这里,他将停到文本的最后一个
。让他偷懒是通过在后面添加一个
,这样匹配的字符就尽可能少。哦,对不起,我错了,你的正则表达式仍然有效。这是因为默认情况下,
将不匹配换行符。这里不需要懒惰,我的坏…好的,谢谢你的解释,但是在这种情况下,它可以工作,直到最后一个
才替换所有字符,但是只有在找到第一个模式之后,即
版本:“xxxx”
。你的意思是说在其他情况下,
*
会过于宽容吗?你需要让
*
变得懒惰,否则它就不起作用了。您的正则表达式将从
version
匹配到
'rest',
这里您所说的“懒惰”是什么意思?我的代码可以工作,但我可以改进我的正则表达式;-)默认情况下,
*
是贪婪的。这意味着它将匹配尽可能多的字符。在这里,他将停到文本的最后一个
。让他偷懒是通过在后面添加一个
,这样匹配的字符就尽可能少。哦,对不起,我错了,你的正则表达式仍然有效。这是因为默认情况下,
将不匹配换行符。这里不需要懒惰,我的坏…好的,谢谢你的解释,但是在这种情况下,它可以工作,直到最后一个
才替换所有字符,但是只有在找到第一个模式之后,即
版本:“xxxx”
。你是说在其他情况下,
*
会过于宽容吗?