首页 > 解决方案 > 了解 powershell 正则表达式

问题描述

早晨

在我的虚拟机上,我安装了 IIS,并调用了一些测试网站设置

Test1.mav359.co.uk
Test2.mav359.co.uk
Test3.mav359.co.uk

我的目标是为 Web 开发人员及其本地站点动态创建一个主机文件,另一个用户帮助我使用以下代码


 $Array = Get-IISSite | ForEach-Object {
    if ($_.ID -gt 1) {
        '{1}    {0}' -f ($_.Name -replace '^(\w+\d+)', '$1-local'),
                        $(if ($_.Name -like '*mav359*') { $IP1 } else { $IP2 })
    }

}

这很好用,正是我需要的,并输出以下内容

10.0.0.1    Test1-local.mav359.co.uk
10.0.0.1    test2-local.mav359.co.uk
10.0.0.1    test3-local.mav359.co.uk

完美但....

我不明白这部分代码是如何工作的

'^(\w+\d+)',

我认为 \w+ = 到 test 的文本 & \d+ = 到数字 eg.1 所以 \test+\1+

我不明白....它只是查看完整网站名称的 test1 部分,它怎么知道在 .mav359.co.uk 之前插入 -local

我不确定代码如何定义其查看的名称部分

抱歉这个愚蠢的问题,但我想知道它为什么有效,而不仅仅是它有效

干杯

标签: regexpowershell

解决方案


正则表达式^(\w+\d+)只是从字符串开头捕获以单词字符开头并以一位或多位数字结尾的部分。

在您的示例中,这将是Test1,test2test3

替换部件然后用它自己 ( $1) 替换捕获的部件,然后-local

详细地:

^             Assert position at the beginning of the string
(             Match the regex below and capture its match into backreference number 1
   \w         Match a single character that is a “word character” (Unicode; any letter or ideograph, digit, connector punctuation)
      +       Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   \d         Match a single character that is a “digit” (any decimal number in any Unicode script)
      +       Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)

推荐阅读