首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用PowerShell进行复杂查找/替换

使用PowerShell进行复杂查找/替换
EN

Stack Overflow用户
提问于 2012-07-12 00:37:14
回答 1查看 247关注 0票数 0

我想在以下示例中添加html链接:

  1. BZ#01234啦
  2. BZ#0124啦
  3. Blah 012345 Blah Blah
  4. BZ#123,345,567,2341 Blah

所以看起来:

  1. BZ#01234啦
  2. BZ#0124啦
  3. Blah 012345 Blah Blah
  4. BZ#123,345,567,2341 Blah

因此,我想这是一个正则表达式的工作,以找到匹配,和一些PowerShell魔术,以添加html链接。我认为regex是((BZ#)|(BZ ))[0-9]+来匹配所有的东西,除了复杂的例子,但是我对regex还不太了解,无法确定,也不知道如何在PowerShell中测试它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-12 01:16:44

我认为这是可行的,这取决于输入的变量。

代码语言:javascript
复制
$inputstring = @'
Blah Blah Blah BZ#01234 Blah Blah Blah
Blah Blah Blah BZ#0124 Blah Blah Blah
Blah Blah Blah BZ 012345 Blah Blah Blah
Blah Complex Blah BZ#123 , 345, 567,2341 Blah
'@

# Split the input into an array of strings
$lines = $inputstring -split '[\r\n]'

# Setup patterns to match against
$pattern1 = "(.*)\sBZ#(\d+) , (\d+), (\d+),(\d+) (.*)"
$pattern2 = "(.*)\sBZ#(\d+)\s(.*)"
$pattern3 = "(.*)\sBZ (\d+)\s(.*)"

# Loop through each line
for($i = 0; $i -lt $lines.count; $i++)
{
    # Start off assuming the current line produces no output
    $output = ""

    # Look for volumes with drive letters
    if($lines[$i] -match $pattern1)
    {
        $output = $matches[1] + " <a href=`"http://bz.com/show_bug.cgi?id=" + $matches[2] + "`">BZ#" + $matches[2] + "</a> , " + 
            "<a href=`"http://bz.com/show_bug.cgi?id=" + $matches[3] + "`">" + $matches[3] + "</a>, " + 
            "<a href=`"http://bz.com/show_bug.cgi?id=" + $matches[4] + "`">" + $matches[4] + "</a>," + 
            "<a href=`"http://bz.com/show_bug.cgi?id=" + $matches[5] + "`">" + $matches[5] + "</a> " + 
            $matches[6]
    }
    elseif($lines[$i] -match $pattern2)
    {
        $output = $matches[1] + " <a href=`"http://bz.com/show_bug.cgi?id=" + $matches[2] + "`">BZ#" + $matches[2] + "</a> " + $matches[3]
    }
    elseif($lines[$i] -match $pattern3)
    {
        $output = $matches[1] + " <a href=`"http://bz.com/show_bug.cgi?id=" + $matches[2] + "`">BZ " + $matches[2] + "</a> " + $matches[3]
    }

    # Write out any output that was produced
    if($output -ne "")
    {
        $output
    }
}

输出:

代码语言:javascript
复制
Blah Blah Blah <a href="http://bz.com/show_bug.cgi?id=01234">BZ#01234</a> Blah Blah Blah
Blah Blah Blah <a href="http://bz.com/show_bug.cgi?id=0124">BZ#0124</a> Blah Blah Blah
Blah Blah Blah <a href="http://bz.com/show_bug.cgi?id=012345">BZ 012345</a> Blah Blah Blah
Blah Complex Blah <a href="http://bz.com/show_bug.cgi?id=123">BZ#123</a> , <a href="http://bz.com/show_bug.cgi?id=345">345</a>, <a href="http://bz.com/show_bug.cgi?id=567">567</a>,<a href="http://bz.com/show_bug.cgi?id=2341">2341</a> Blah
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11443566

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档