【问题标题】:String replacement function with PowershellPowershell 的字符串替换功能
【发布时间】:2017-10-27 00:58:56
【问题描述】:

我正在拼命尝试将以下函数从 PHP 改编为 Powershell:

函数 lgReplace($origString,$repArray)

{
    // Transforms an input string containing terms like %1%, %2% and so on by values in array
    for($i=1;$i<count($repArray)+1;$i++)
    {
        $origString=str_replace("%$i%",$repArray[$i],$origString);
    }
    return $origString;
}

在php中,你可以这样调用这个函数:

$source="I like %1% and %2% !";
$new=lgReplace($source, array(1=>"drinking beer",2=>"coding")

也就是说,函数会在 $source 中查找“%1%”,将其更改为“drinking beer”,然后在 $source 中查找“%2%”,将其替换为“coding”,然后返回结果是“我喜欢喝啤酒和编码!”。

我尝试将此功能适配到powershell,但失败了:

function lgReplace($origString,$repArray)
{
    # Transforms an input string containing terms like %1%, %2% and so on by values in array
    for($i=1;$i -lt $repArray.count+1;$i++)
    {
        $origString=$origString -replace "%$i%",$repArray[$i]
    }
    return $origString
}

$source="I like %1% and %2% !"
$terms=@("coding","drinking beer")
$new=lgReplace $source,$terms
$new

$new 显示这个:

I like %1% and %2% !
coding
drinking beer

我尝试了几种方法来完成这项工作,但无济于事......任何帮助将不胜感激! 谢谢!

【问题讨论】:

  • 你可以这样做cls;$repArray = "drinking", "coding";Write-Output ("I like {0} and {1} !" -f $repArray)
  • 谢谢马丁,帮了我很多!我不知道如何给你应得的功劳,我是 Stackoverflow 的新手...
  • 看来其他人也有同样的想法,所以您可以接受他们的回答。
  • 你是个绅士!

标签: string powershell replace


【解决方案1】:

尝试这样的事情(en passant j'adore ton pseudo)

$source="I like {0} and {1} !"
$terms=@("coding","drinking beer")
$new=$source -f $terms
$new

【讨论】:

  • 感谢 Esperento57 !就像一个魅力,马丁的评论也帮助了我很多!
【解决方案2】:

我更愿意为 [Key - Value] 映射使用哈希表。

$replaceMe = 'I like %1%, %2%, %3%, %4% and %5%'

$keyValueMap = @{
  '%1%' = 'Jägermeister'; 
  '%2%' = 'My wife'; 
  '%3%' = 'PowerShell'; 
  '%4%' = 'the moon';
  '%5%' = 'Hashtable performance'
}

$keyValueMap.GetEnumerator() | % {$replaceMe = $replaceMe -replace $_.key, $_.value }
Write-host $replaceMe 

如果我想在 PowerShell 中比较数据结构,我不会工作 使用数组。

在 .NET 中,数组是不可变的。每次添加新项目时,系统都会重建数组并追加新数据。

每增加一个新项目,您的数组就会变得越来越慢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 2011-09-18
    • 2014-09-20
    相关资源
    最近更新 更多