regex - 了解 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
我不确定代码如何定义其查看的名称部分
抱歉这个愚蠢的问题,但我想知道它为什么有效,而不仅仅是它有效
干杯
解决方案
正则表达式^(\w+\d+)
只是从字符串开头捕获以单词字符开头并以一位或多位数字结尾的部分。
在您的示例中,这将是Test1
,test2
和test3
。
替换部件然后用它自己 ( $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)
)
推荐阅读
- c - 为什么我的代码逐个字母而不是逐句打印出来?
- linux - 如何查找进程是否正在运行?
- php - 以管理员身份登录时无法访问用户注册或登录页面
- matlab - 使用递归洪水填充的 Matlab 图像斑点检测
- arrays - 递归比较两个数组而不使用循环[伪代码]
- ms-access - Microsoft Access 如何在失去焦点时阻止滚动的文本字段返回顶部(如滚动到顶部)
- javascript - Angular订阅推送对象到数组
- command-line-interface - Activate the applications on ONOS in GNS3
- c# - Error "Incorrect Content Type" when sending parameter in ajax datatable to ASP.NET Core 2.0
- android - 如何在 javafx 应用程序中连接 Godaddy mysql